UNPKG

@iden3/js-iden3-core

Version:

Low level API to create and manipulate iden3 Claims.

3 lines (2 loc) 28.2 kB
import{poseidon as t,sha256 as e,Hex as r,base58FromBytes as n,base58ToBytes as i}from"@iden3/js-crypto";const s=Object.freeze({ERRORS:{DATA_OVERFLOW:new Error("data does not fits SNARK size"),INCORRECT_ID_POSITION:new Error("incorrect ID position"),NO_ID:new Error("ID is not set"),INVALID_SUBJECT_POSITION:new Error("invalid subject position"),INCORRECT_MERKLIZED_POSITION:new Error("incorrect Merklize position"),NO_MERKLIZED_ROOT:new Error("Merklized root is not set"),NETWORK_NOT_SUPPORTED_FOR_DID:new Error("network in not supported for did"),UNSUPPORTED_BLOCKCHAIN_FOR_DID:new Error("not supported blockchain for did"),UNSUPPORTED_DID_METHOD:new Error("not supported DID method"),UNKNOWN_DID_METHOD:new Error("unknown DID method"),INCORRECT_DID:new Error("incorrect DID"),UNSUPPORTED_ID:new Error("unsupported Id")},SCHEMA:{HASH_LENGTH:16},ETH_ADDRESS_LENGTH:20,BYTES_LENGTH:32,ELEM_BYTES_LENGTH:4,NONCE_BYTES_LENGTH:8,Q:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),ID:{TYPE_DEFAULT:Uint8Array.from([0,0]),TYPE_READONLY:Uint8Array.from([0,1]),ID_LENGTH:31},DID:{DID_SCHEMA:"did"},GENESIS_LENGTH:27}),o={Ethereum:"eth",Polygon:"polygon",Privado:"privado",Linea:"linea",Unknown:"unknown",NoChain:"",ReadOnly:"readonly"},a={Main:"main",Mumbai:"mumbai",Amoy:"amoy",Goerli:"goerli",Sepolia:"sepolia",Zkevm:"zkevm",Cardona:"cardona",Test:"test",Unknown:"unknown",NoNetwork:""},h={Iden3:"iden3",PolygonId:"polygonid",Other:""},l={[`${o.Ethereum}:${a.Main}`]:1,[`${o.Ethereum}:${a.Goerli}`]:5,[`${o.Ethereum}:${a.Sepolia}`]:11155111,[`${o.Polygon}:${a.Main}`]:137,[`${o.Polygon}:${a.Mumbai}`]:80001,[`${o.Polygon}:${a.Amoy}`]:80002,[`${o.Polygon}:${a.Zkevm}`]:1101,[`${o.Polygon}:${a.Cardona}`]:2442,[`${o.Privado}:${a.Main}`]:21e3,[`${o.Privado}:${a.Test}`]:21001,[`${o.Linea}:${a.Main}`]:59144,[`${o.Linea}:${a.Sepolia}`]:59141},u={[h.Iden3]:1,[h.PolygonId]:2,[h.Other]:255},c={[`${o.ReadOnly}:${a.NoNetwork}`]:0,[`${o.Polygon}:${a.Main}`]:17,[`${o.Polygon}:${a.Mumbai}`]:18,[`${o.Polygon}:${a.Amoy}`]:19,[`${o.Polygon}:${a.Zkevm}`]:20,[`${o.Polygon}:${a.Cardona}`]:21,[`${o.Ethereum}:${a.Main}`]:33,[`${o.Ethereum}:${a.Goerli}`]:34,[`${o.Ethereum}:${a.Sepolia}`]:35,[`${o.Privado}:${a.Main}`]:161,[`${o.Privado}:${a.Test}`]:162,[`${o.Linea}:${a.Main}`]:73,[`${o.Linea}:${a.Sepolia}`]:72},d={[h.Iden3]:{...c},[h.PolygonId]:{...c},[h.Other]:{[`${o.Unknown}:${a.Unknown}`]:255}},I=new TextEncoder;function g(t){const e=BigInt(256);let r=BigInt(0),n=BigInt(1);return t.forEach((t=>{r+=n*BigInt(t),n*=e})),r}function E(t){return g(t.reverse())}function f(t,e=31){const r=BigInt(256),n=new Uint8Array(e);let i=0;for(;t>BigInt(0);)n[i]=Number(t%r),t/=r,i+=1;return n}function y(t,e=31){return f(t,e).reverse()}function w(t){const e=new ArrayBuffer(4);return new DataView(e).setUint32(0,t,!0),new Uint8Array(e)}function m(t){const e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return new DataView(e).getUint32(0,!0)}function _(t){const e=new ArrayBuffer(8);return new DataView(e).setBigUint64(0,t,!0),new Uint8Array(e)}function S(t){const e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return new DataView(e).getBigUint64(0,!0)}function b(t){return Math.floor(t.getTime()/1e3)}function p(t){return new Date(1e3*t)}function x(t){return t<s.Q}function N(t){return t.every((t=>x(t)))}function D(e,r,n){return t.hash([e,r,n])}class O{static isNotValidIDChar(t){return O.isNotAlpha(t)&&O.isNotDigit(t)&&"."!==t&&"-"!==t}static isNotValidParamChar(t){return O.isNotAlpha(t)&&O.isNotDigit(t)&&"."!==t&&"-"!==t&&"_"!==t&&":"!==t}static isNotValidQueryOrFragmentChar(t){return O.isNotValidPathChar(t)&&"/"!==t&&"?"!==t}static isNotValidPathChar(t){return O.isNotUnreservedOrSubdelim(t)&&":"!==t&&"@"!==t}static isNotUnreservedOrSubdelim(t){switch(t){case"-":case".":case"_":case"~":case"!":case"$":case"&":case"'":case"(":case")":case"*":case"+":case",":case";":case"=":return!1;default:return!(!O.isNotAlpha(t)||!O.isNotDigit(t))}}static isNotHexDigit(t){return O.isNotDigit(t)&&(t<"A"||t>"F")&&(t<"a"||t>"f")}static isNotDigit(t){return t<"0"||t>"9"}static isNotAlpha(t){return O.isNotSmallLetter(t)&&O.isNotBigLetter(t)}static isNotBigLetter(t){return t<"A"||t>"Z"}static isNotSmallLetter(t){return t<"a"||t>"z"}}const T=t=>Uint8Array.from([...new Uint8Array(7),...t]);class R{static intToBytes(t){return R.intToNBytes(t,s.BYTES_LENGTH)}static intToNBytes(t,e){return Uint8Array.from(f(t,e))}static checkChecksum(t){const{typ:e,genesis:r,checksum:n}=R.decomposeBytes(t);if(!n.length||JSON.stringify(Uint8Array.from([0,0]))===JSON.stringify(n))return!1;const i=R.calculateChecksum(e,r);return JSON.stringify(i)===JSON.stringify(n)}static decomposeBytes(t){const e=t.length-2;return{typ:t.slice(0,2),genesis:t.slice(2,e),checksum:t.slice(-2)}}static calculateChecksum(t,e){const r=[...t,...e].reduce(((t,e)=>t+e),0),n=[r>>8,255&r];return Uint8Array.from(n.reverse())}static hashBytes(t){const r=e(I.encode(t));return new Uint8Array(r)}static hexToBytes(t){return r.decodeString(t)}static bytesToHex(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r]<0?t[r]+256:t[r];e.push((n>>>4).toString(16)),e.push((15&n).toString(16))}return e.join("")}static bytesToInt(t){return g(t)}}class B{constructor(t){if(this._bytes=new Uint8Array(s.BYTES_LENGTH),t&&(this._bytes=t),this._bytes.length!==s.BYTES_LENGTH)throw new Error("Invalid bytes length")}get bytes(){return this._bytes}set bytes(t){this._bytes=t}toBigInt(){return R.bytesToInt(this._bytes)}setBigInt(t){if(!x(t))throw s.ERRORS.DATA_OVERFLOW;return this._bytes=R.intToBytes(t),this}slotFromHex(t){const e=r.decodeString(t);if(e.length!==s.BYTES_LENGTH)throw new Error("Invalid bytes length");return this._bytes.set(e,0),this}hex(){return r.encodeString(this._bytes)}static elemBytesToInts(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r];e.push(n.toBigInt())}return e}static fromInt(t){if(!x(t))throw s.ERRORS.DATA_OVERFLOW;const e=R.intToBytes(t);return new B(e)}}class k{constructor(t){if(this._bytes=new Uint8Array(s.SCHEMA.HASH_LENGTH),t&&(this._bytes=t),this.bytes.length!==s.SCHEMA.HASH_LENGTH)throw new Error(`Schema hash must be ${s.SCHEMA.HASH_LENGTH} bytes long`)}get bytes(){return this._bytes}marshalTextBytes(){return r.encode(this.bytes)}marshalText(){return r.encodeString(this.bytes)}static newSchemaHashFromHex(t){const e=r.decodeString(t);if(e.length!==s.SCHEMA.HASH_LENGTH)throw new Error(`invalid schema hash length: ${e.length}`);return new k(e)}static newSchemaHashFromInt(t){const e=R.intToNBytes(t,s.SCHEMA.HASH_LENGTH),r=s.SCHEMA.HASH_LENGTH-e.length;return new k(R.intToBytes(t).slice(r,s.SCHEMA.HASH_LENGTH))}bigInt(){return R.bytesToInt(this.bytes)}}k.authSchemaHash=new k(Uint8Array.from([204,163,55,26,108,177,183,21,0,68,7,227,37,189,153,60]));class ${constructor(t,e){this._checksum=R.calculateChecksum(t,e),this._bytes=Uint8Array.from([...t,...e,...this._checksum])}static getFromBytes(t){const{typ:e,genesis:r}=R.decomposeBytes(t);return new $(e,r)}checksum(){return this._checksum}string(){return n(this._bytes)}get bytes(){return this._bytes}set bytes(t){this._bytes=t}type(){return this._bytes.slice(0,2)}bigInt(){return g(this._bytes)}equal(t){return JSON.stringify(this._bytes)===JSON.stringify(t.bytes)}marshal(){return(new TextEncoder).encode(this.string())}static unMarshal(t){return $.fromString((new TextDecoder).decode(t))}static fromBytes(t){const e=t??Uint8Array.from([]);if(e.length!==s.ID.ID_LENGTH)throw new Error("fromBytes error: byte array incorrect length");if(e.every((t=>0===t)))throw new Error("fromBytes error: byte array empty");const r=$.getFromBytes(e);if(!R.checkChecksum(e))throw new Error("fromBytes error: checksum error");return r}static fromString(t){const e=i(t);return $.fromBytes(e)}static fromBigInt(t){const e=R.intToNBytes(t,s.ID.ID_LENGTH);return $.fromBytes(e)}static profileId(e,r){const n=t.hash([e.bigInt(),r]),{typ:i}=R.decomposeBytes(e.bytes),s=R.intToNBytes(n,27);return new $(i,s)}static idGenesisFromIdenState(t,e){const r=B.fromInt(e),n=r.bytes.slice(r.bytes.length-27);return new $(t,n)}static ethAddressFromId(t){if(!t.bytes.slice(2,9).every((t=>0===t)))throw new Error("can't get Ethereum address: high bytes of genesis are not zero");return t.bytes.slice(9).slice(0,s.ETH_ADDRESS_LENGTH)}}var H,A,U,v,V,L;!function(t){t.IndexA="IndexA",t.IndexB="IndexB",t.ValueA="ValueA",t.ValueB="ValueB"}(H||(H={}));class M extends Error{constructor(t){super(`Slot ${t} not in field (too large)`),Object.setPrototypeOf(this,M.prototype)}}!function(t){t[t.Self=0]="Self",t[t.Invalid=1]="Invalid",t[t.OtherIdenIndex=2]="OtherIdenIndex",t[t.OtherIdenValue=3]="OtherIdenValue"}(A||(A={})),function(t){t[t.None=0]="None",t[t.Index=1]="Index",t[t.Value=2]="Value"}(U||(U={})),function(t){t[t.None=0]="None",t[t.Index=32]="Index",t[t.Value=64]="Value",t[t.Invalid=128]="Invalid"}(v||(v={})),function(t){t[t.None=0]="None",t[t.Index=1]="Index",t[t.Value=2]="Value"}(V||(V={})),function(t){t[t.ByteIdx=16]="ByteIdx",t[t.ExpirationBitIdx=3]="ExpirationBitIdx",t[t.UpdatableBitIdx=4]="UpdatableBitIdx"}(L||(L={}));class P{constructor(){this._index=[],this._value=[];for(let t=0;t<s.ELEM_BYTES_LENGTH;t++)this._index[t]=new B,this._value[t]=new B}static newClaim(t,...e){const r=new P;r.setSchemaHash(t);for(let t=0;t<e.length;t++){(0,e[t])(r)}return r}getSchemaHash(){return new k(this._index[0].bytes.slice(0,s.SCHEMA.HASH_LENGTH))}get value(){return this._value}set value(t){this._value=t}get index(){return this._index}set index(t){this._index=t}setSchemaHash(t){this._index[0]=new B(Uint8Array.from([...t.bytes,...new Array(s.SCHEMA.HASH_LENGTH).fill(0)]))}setSubject(t){this._index[0].bytes[L.ByteIdx]&=248,this._index[0].bytes[L.ByteIdx]|=t}getSubject(){let t=this._index[0].bytes[L.ByteIdx];return t&=7,t}setFlagExpiration(t){t?this._index[0].bytes[L.ByteIdx]|=1<<L.ExpirationBitIdx:this._index[0].bytes[L.ByteIdx]&=~(1<<L.ExpirationBitIdx)}getFlagExpiration(){const t=1<<L.ExpirationBitIdx;return(this._index[0].bytes[L.ByteIdx]&t)>0}getIdPosition(){switch(this.getSubject()){case A.Self:return U.None;case A.OtherIdenIndex:return U.Index;case A.OtherIdenValue:return U.Value;default:throw s.ERRORS.INVALID_SUBJECT_POSITION}}setValueDataInts(t,e){this._value[2]=this.setSlotInt(t,H.ValueA),this._value[3]=this.setSlotInt(e,H.ValueB)}setValueDataBytes(t,e){this._value[2]=this.setSlotBytes(t,H.ValueA),this._value[3]=this.setSlotBytes(e,H.ValueB)}setValueData(t,e){if(!N([t.toBigInt(),e.toBigInt()]))throw s.ERRORS.DATA_OVERFLOW;this._value[2]=t,this._value[3]=e}setIndexDataInts(t,e){this._index[2]=this.setSlotInt(t,H.IndexA),this._index[3]=this.setSlotInt(e,H.IndexB)}setIndexDataBytes(t,e){this._index[2]=this.setSlotBytes(t,H.IndexA),this._index[3]=this.setSlotBytes(e,H.IndexB)}setSlotBytes(t,e){const r=new B(t);if(!x(r.toBigInt()))throw new M(e);return r}setFlagMerklized(t){let e;switch(t){case V.Index:e=v.Index;break;case V.Value:e=v.Value;break;default:e=v.None}this.index[0].bytes[L.ByteIdx]&=31,this.index[0].bytes[L.ByteIdx]|=e}getMerklized(){let t=this.index[0].bytes[L.ByteIdx];return t&=224,t}getMerklizedPosition(){switch(this.getMerklized()){case v.None:return V.None;case v.Index:return V.Index;case v.Value:return V.Value;default:throw s.ERRORS.INCORRECT_MERKLIZED_POSITION}}setSlotInt(t,e){if(t||(t=BigInt(0)),!x(t))throw new M(e);return(new B).setBigInt(t)}setIndexData(t,e){if(!N([t.toBigInt(),e.toBigInt()]))throw s.ERRORS.DATA_OVERFLOW;this._index[2]=t,this._index[3]=e}resetExpirationDate(){this.setFlagExpiration(!1);const t=Array.from({length:s.NONCE_BYTES_LENGTH},(()=>0)),e=Array.from(this._value[0].bytes);e.splice(s.NONCE_BYTES_LENGTH,s.NONCE_BYTES_LENGTH,...t),this._value[0]=new B(Uint8Array.from(e))}getExpirationDate(){if(this.getFlagExpiration()){const t=S(this._value[0].bytes.slice(8,16));return p(Number(t))}return null}setExpirationDate(t){this.setFlagExpiration(!0);const e=_(BigInt(b(t))),r=Array.from(this._value[0].bytes);r.splice(s.NONCE_BYTES_LENGTH,s.NONCE_BYTES_LENGTH,...e),this._value[0]=new B(Uint8Array.from(r))}getRevocationNonce(){return S(this._value[0].bytes.slice(0,8))}setRevocationNonce(t){const e=_(t);if(e.length>s.NONCE_BYTES_LENGTH)throw new Error("Nonce length is not valid");const r=Array.from(this._value[0].bytes);r.splice(0,s.NONCE_BYTES_LENGTH,...e),this._value[0]=new B(Uint8Array.from(r))}getValueId(){return $.fromBytes(this._value[1].bytes.slice(0,-1))}setValueId(t){this.resetIndexId(),this.setSubject(A.OtherIdenValue);const e=Array.from(this._index[1].bytes);e.splice(0,t.bytes.length,...t.bytes),this._value[1]=new B(Uint8Array.from(e))}resetIndexId(){this._index[1]=new B(new Uint8Array(s.BYTES_LENGTH).fill(0))}resetValueId(){this._value[1]=new B(new Uint8Array(s.BYTES_LENGTH).fill(0))}getIndexId(){return $.fromBytes(this._index[1].bytes.slice(0,-1))}setIndexId(t){this.resetValueId(),this.setSubject(A.OtherIdenIndex);const e=Array.from(this._index[1].bytes);e.splice(0,t.bytes.length,...t.bytes),this._index[1]=new B(Uint8Array.from(e))}setVersion(t){const e=w(t);this._index[0].bytes[20]=e[0],this._index[0].bytes[21]=e[1],this._index[0].bytes[22]=e[2],this._index[0].bytes[23]=e[3]}getVersion(){return m(this._index[0].bytes.slice(20,24))}setFlagUpdatable(t){t?this._index[0].bytes[L.ByteIdx]|=1<<L.UpdatableBitIdx:this._index[0].bytes[L.ByteIdx]&=~(1<<L.UpdatableBitIdx)}hIndex(){return t.hash(B.elemBytesToInts(this._index))}getFlagUpdatable(){const t=1<<L.UpdatableBitIdx;return(this._index[0].bytes[L.ByteIdx]&t)>0}hValue(){return t.hash(B.elemBytesToInts(this._value))}hiHv(){return{hi:this.hIndex(),hv:this.hValue()}}setIndexMerklizedRoot(t){this.resetValueMerklizedRoot(),this.setFlagMerklized(V.Index),this.index[2]=this.setSlotInt(t,H.IndexA)}resetIndexMerklizedRoot(){this._index[2]=new B(new Uint8Array(s.BYTES_LENGTH).fill(0))}setValueMerklizedRoot(t){this.resetIndexMerklizedRoot(),this.setFlagMerklized(V.Value),this.value[2]=this.setSlotInt(t,H.ValueA)}resetValueMerklizedRoot(){this._value[2]=new B(new Uint8Array(s.BYTES_LENGTH).fill(0))}getMerklizedRoot(){switch(this.getMerklized()){case v.Index:return this.index[2].toBigInt();case v.Value:return this.value[2].toBigInt();default:throw s.ERRORS.NO_MERKLIZED_ROOT}}resetId(){this.resetIndexId(),this.resetValueId(),this.setSubject(A.Self)}getId(){switch(this.getSubject()){case A.OtherIdenIndex:return this.getIndexId();case A.OtherIdenValue:return this.getValueId();default:throw s.ERRORS.NO_ID}}rawSlots(){return{index:this._index,value:this._value}}rawSlotsAsInts(){return[...B.elemBytesToInts(this._index),...B.elemBytesToInts(this._value)]}clone(){return JSON.parse(JSON.stringify(this))}marshalJson(){return this.rawSlotsAsInts().map((t=>t.toString()))}unMarshalJson(t){const e=JSON.parse(t).map((t=>BigInt(t)));if(e.length!==this._index.length+this._value.length)throw new Error("invalid number of claim's slots");this._index=[],this._value=[];for(let t=0,r=s.ELEM_BYTES_LENGTH;t<e.length/2;t++,r++)this._index[t]=new B,this._index[t].setBigInt(e[t]),this._value[t]=new B,this._value[t].setBigInt(e[r]);return this}marshalBinary(){const t=t=>t.reduce(((t,e)=>[...t,...e.bytes]),[]);return Uint8Array.from(t(this._index).concat(t(this._value)))}hex(){const t=this.marshalBinary();return r.encodeString(t)}fromHex(t){const e=r.decodeString(t);return this.unMarshalBinary(e),this}unMarshalBinary(t){const e=2*s.ELEM_BYTES_LENGTH*s.BYTES_LENGTH;if(t.length!==e)throw new Error("unexpected length of input data");this._index=[],this._value=[];for(let e=0,r=s.ELEM_BYTES_LENGTH;e<s.ELEM_BYTES_LENGTH;e++,r++)this._index[e]=new B(t.slice(e*s.BYTES_LENGTH,(e+1)*s.BYTES_LENGTH)),this._value[e]=new B(t.slice(r*s.BYTES_LENGTH,(r+1)*s.BYTES_LENGTH))}}class C{static withFlagUpdatable(t){return e=>e.setFlagUpdatable(t)}static withVersion(t){return e=>e.setVersion(t)}static withIndexId(t){return e=>e.setIndexId(t)}static withValueId(t){return e=>e.setValueId(t)}static withFlagMerklized(t){return e=>e.setFlagMerklized(t)}static withId(t,e){return r=>{switch(e){case U.Index:r.setIndexId(t);break;case U.Value:r.setValueId(t);break;default:throw s.ERRORS.INCORRECT_ID_POSITION}}}static withRevocationNonce(t){return e=>e.setRevocationNonce(t)}static withExpirationDate(t){return e=>e.setExpirationDate(t)}static withIndexData(t,e){return r=>r.setIndexData(t,e)}static withIndexDataBytes(t,e){return r=>r.setIndexDataBytes(t,e)}static withIndexDataInts(t,e){return r=>r.setIndexDataInts(t,e)}static withValueData(t,e){return r=>r.setValueData(t,e)}static withValueDataBytes(t,e){return r=>r.setValueDataBytes(t,e)}static withValueDataInts(t,e){return r=>r.setValueDataInts(t,e)}static withIndexMerklizedRoot(t){return e=>{e.setFlagMerklized(V.Index),e.index[2]=e.setSlotInt(t,H.IndexA)}}static withValueMerklizedRoot(t){return e=>{e.setFlagMerklized(V.Value),e.value[2]=e.setSlotInt(t,H.ValueA)}}static withMerklizedRoot(t,e){return r=>{switch(e){case V.Index:r.setFlagMerklized(V.Index),r.index[2]=r.setSlotInt(t,H.IndexA);break;case V.Value:r.setFlagMerklized(V.Value),r.value[2]=r.setSlotInt(t,H.ValueA);break;default:throw s.ERRORS.INCORRECT_MERKLIZED_POSITION}}}}class F{constructor(t,e){this.blockchain=t,this.networkId=e}toString(){return`${this.blockchain}:${this.networkId}`}static fromString(t){const[e,r]=t.split(":");return new F(e.replace("_",""),r.replace("_",""))}}function G(t,e,r){const n=u[t];if(!n)throw s.ERRORS.UNSUPPORTED_DID_METHOD;const i=d[t];if(!i)throw s.ERRORS.NETWORK_NOT_SUPPORTED_FOR_DID;const o=i[new F(e,r).toString()];if("number"!=typeof o)throw new Error(`blockchain ${e.toString()??"-"} and network ${r.toString()??"-"} is not defined in core lib`);return Uint8Array.from([n,o])}function z(t,e){const r=d[t];if(!r)throw s.ERRORS.UNSUPPORTED_DID_METHOD;for(const[t,n]of Object.entries(r))if(n===e)return F.fromString(t).networkId;throw s.ERRORS.NETWORK_NOT_SUPPORTED_FOR_DID}function Y(t,e){const r=d[t];if(!r)throw new Error(`${s.ERRORS.NETWORK_NOT_SUPPORTED_FOR_DID}: did method ${t} is not defined in core lib`);for(const[t,n]of Object.entries(r))if(n===e)return F.fromString(t).blockchain;throw s.ERRORS.UNSUPPORTED_BLOCKCHAIN_FOR_DID}function j(t){for(const[e,r]of Object.entries(u))if(r===t)return e;throw s.ERRORS.UNSUPPORTED_DID_METHOD}class K{constructor(t,e){this.name=t,this.value=e}toString(){return this.name?this.value?`${this.name}=${this.value}`:this.name:""}}const J=Object.freeze({method:"",id:"",idStrings:[],params:[],path:"",pathSegments:[],query:"",fragment:""});class W{constructor(t){this.input=t,this.currentIndex=0,this.out={...J}}checkLength(){if(this.input.length<7)throw new Error("input length is less than 7");return this.parseScheme.bind(this)}parseScheme(){if("did:"!==this.input.slice(0,4))throw new Error("input does not begin with 'did:' prefix");return this.currentIndex=3,this.parseMethod.bind(this)}parseMethod(){const t=this.input,e=t.length;let r=this.currentIndex+1;const n=r;for(;;){if(r===e)throw new Error("input does not have a second `:` marking end of method name");const i=t[r];if(":"===i){if(r===n)throw new Error(`method is empty, ${r}`);break}if(O.isNotDigit(i)&&O.isNotSmallLetter(i))throw new Error(`"character is not a-z OR 0-9, ${r}`);r+=1}return this.currentIndex=r,this.out.method=t.slice(n,r),this.parseId.bind(this)}parseId(){const t=this.input,e=t.length;let r=this.currentIndex+1;const n=r;let i=null;for(;;){if(r===e){i=null;break}const n=t[r];if(":"===n){i=this.parseId;break}if(";"===n){i=this.parseParamName;break}if("/"===n){i=this.parsePath;break}if("?"===n){i=this.parseQuery;break}if("#"===n){i=this.parseFragment;break}if(O.isNotValidIDChar(n))throw new Error(`byte is not ALPHA OR DIGIT OR '.' OR '-', ${r}`);r+=1}if(r===n)throw new Error(`idstring must be at least one char long, ${r}`);return this.currentIndex=r,this.out.idStrings=[...this.out.idStrings,t.slice(n,r)],i?i.bind(this):null}parseParamName(){const t=this.input,e=this.currentIndex+1,r=this.paramTransition(),n=this.currentIndex;if(n===e)throw new Error(`Param name must be at least one char long, ${n}`);return this.out.params=[...this.out.params,new K(t.slice(e,n),"")],r?r.bind(this):null}parseParamValue(){const t=this.input,e=this.currentIndex+1,r=this.paramTransition(),n=this.currentIndex;return this.out.params[this.out.params.length-1].value=t.slice(e,n),r?r.bind(this):null}paramTransition(){const t=this.input,e=t.length;let r,n,i,s=this.currentIndex+1;for(;;){if(s===e){n=null;break}const o=t[s];if(";"===o){n=this.parseParamName;break}if("="===o){n=this.parseParamValue;break}if("/"===o){n=this.parsePath;break}if("?"===o){n=this.parseQuery;break}if("#"==o){n=this.parseFragment;break}if("%"==o){if(s+2>=e||O.isNotHexDigit(t[s+1])||O.isNotHexDigit(t[s+2]))throw new Error(`% is not followed by 2 hex digits', ${s}`);i=!0,r=3}else i=!1,r=1;if(!i&&O.isNotValidParamChar(o))throw new Error(`character is not allowed in param - ${o}', ${s}`);s+=r}return this.currentIndex=s,n?n.bind(this):null}parsePath(){const t=this.input,e=t.length;let r=this.currentIndex+1;const n=r;let i,s,o;for(;;){if(r===e){s=null;break}const n=t[r];if("/"===n){s=this.parsePath;break}if("?"===n){s=this.parseQuery;break}if("%"===n){if(r+2>=e||O.isNotHexDigit(t[r+1])||O.isNotHexDigit(t[r+2]))throw new Error(`% is not followed by 2 hex digits, ${r}`);o=!0,i=3}else o=!1,i=1;if(!o&&O.isNotValidPathChar(n))throw new Error(`character is not allowed in path, ${r}`);r+=i}if(r==n&&0===this.out.pathSegments.length)throw new Error(`first path segment must have at least one character, ${r}`);return this.currentIndex=r,this.out.pathSegments=[...this.out.pathSegments,t.slice(n,r)],s?s.bind(this):null}parseQuery(){const t=this.input,e=t.length;let r=this.currentIndex+1;const n=r;let i,s,o=null;for(;r!==e;){const n=t[r];if("#"===n){o=this.parseFragment;break}if("%"===n){if(r+2>=e||O.isNotHexDigit(t[r+1])||O.isNotHexDigit(t[r+2]))throw new Error(`% is not followed by 2 hex digits, ${r}`);s=!0,i=3}else s=!1,i=1;if(!s&&O.isNotValidQueryOrFragmentChar(n))throw new Error(`character is not allowed in query - ${n}`);r+=i}return this.currentIndex=r,this.out.query=t.slice(n,r),o?o.bind(this):null}parseFragment(){const t=this.input,e=this.input.length;let r=this.currentIndex+1;const n=r;let i,s;for(;r!==e;){const n=t[r];if("%"===n){if(r+2>=e||O.isNotHexDigit(t[r+1])||O.isNotHexDigit(t[r+2]))throw new Error(`% is not followed by 2 hex digits, ${r}`);s=!0,i=3}else s=!1,i=1;if(!s&&O.isNotValidQueryOrFragmentChar(n))throw new Error(`character is not allowed in fragment - ${n}`);r+=i}return this.currentIndex=r,this.out.fragment=t.slice(n,r),null}}class Q{constructor(t){this.method="",this.id="",this.idStrings=[],this.params=[],this.path="",this.pathSegments=[],this.query="",this.fragment="",t&&Object.assign(this,t)}isUrl(){return this.params.length>0||!!this.path||this.pathSegments.length>0||!!this.query||!!this.fragment}string(){const t=["did:"];if(!this.method)return"";if(t.push(`${this.method}:`),this.id)t.push(this.id);else{if(!this.idStrings.length)return"";t.push(this.idStrings.join(":"))}if(this.params.length)for(const e of this.params){const r=e.toString();if(!r)return"";t.push(`;${r}`)}return this.path?t.push(`/${this.path}`):this.pathSegments.length&&t.push(`/${this.pathSegments.join("/")}`),this.query&&t.push(`?${this.query}`),this.fragment&&t.push(`#${this.fragment}`),t.join("")}toJSON(){return this.string()}static parse(t){const e=new W(t);let r=e.checkLength();for(;r;)r=r();return e.out.id=e.out.idStrings.join(":"),e.out.path=e.out.pathSegments.join("/"),new Q(e.out)}static decodePartsFromId(t){const e=j(t.bytes[0]);return{method:e,blockchain:Y(e,t.bytes[1]),networkId:z(e,t.bytes[1])}}static networkIdFromId(t){return Q.throwIfDIDUnsupported(t).networkId}static methodFromId(t){return Q.throwIfDIDUnsupported(t).method}static blockchainFromId(t){return Q.throwIfDIDUnsupported(t).blockchain}static throwIfDIDUnsupported(t){const{method:e,blockchain:r,networkId:n}=Q.decodePartsFromId(t);if(Q.isUnsupported(e,r,n))throw new Error(`${s.ERRORS.UNKNOWN_DID_METHOD.message}: unsupported DID`);return{method:e,blockchain:r,networkId:n}}static newFromIdenState(t,e){const r=$.idGenesisFromIdenState(t,e);return Q.parseFromId(r)}static new(t,e){return Q.parseFromId(new $(t,e))}static parseFromId(t){if(!R.checkChecksum(t.bytes))throw new Error(`${s.ERRORS.UNSUPPORTED_ID.message}: invalid checksum`);const{method:e,blockchain:r,networkId:n}=Q.throwIfDIDUnsupported(t),i=[s.DID.DID_SCHEMA,e.toString(),r.toString()];n&&i.push(n.toString()),i.push(t.string());const o=i.join(":");return Q.parse(o)}static idFromDID(t){let e;try{e=Q.getIdFromDID(t)}catch(e){if(e.message===s.ERRORS.UNKNOWN_DID_METHOD.message)return Q.idFromUnsupportedDID(t);throw e}return e}static isUnsupported(t,e,r){return t==h.Other&&e==o.Unknown&&r==a.Unknown}static idFromUnsupportedDID(t){const r=e(I.encode(t.string())),n=new Uint8Array(27),i=r.slice(r.length-s.GENESIS_LENGTH);for(let t=0;t<n.length;t++)n[t]=i[t]??0;const l=new F(o.Unknown,a.Unknown),c=Uint8Array.from([u[h.Other],d[h.Other][l.toString()]]);return new $(c,n)}static getIdFromDID(t){const e=t.method;if(!u[e]||e===h.Other)throw s.ERRORS.UNKNOWN_DID_METHOD;if(t.idStrings.length>3||t.idStrings.length<2)throw new Error(`${s.ERRORS.INCORRECT_DID}: unexpected number of ID strings`);const r=$.fromString(t.idStrings[t.idStrings.length-1]);if(!R.checkChecksum(r.bytes))throw new Error(`${s.ERRORS.INCORRECT_DID}: incorrect ID checksum`);const{method:n,blockchain:i,networkId:o}=Q.decodePartsFromId(r);if(n.toString()!==e.toString())throw new Error(`${s.ERRORS.INCORRECT_DID}: methods in Id and DID are different`);if(i.toString()!==t.idStrings[0])throw new Error(`${s.ERRORS.INCORRECT_DID}: blockchains in ID and DID are different`);if(t.idStrings.length>2&&o.toString()!=t.idStrings[1])throw new Error(`${s.ERRORS.INCORRECT_DID}: networkIDs in Id and DID are different`);return r}}const Z=t=>{o[t]=t},q=t=>{a[t]=t},X=(t,e)=>{const r=u[h.Other];if(e>=r)throw new Error(`Can't register DID method byte: current '${e.toString(2)}', maximum byte allowed: '${(r-1).toString(2)}'`);if("number"!=typeof u[t]||u[t]!==e){if(Object.values(u).includes(e))throw new Error(`can't register method '${t}' because DID method byte '${e.toString(2)}' already registered for another method`);h[t]=t,u[t]=e}},tt=(t,e,r)=>{const n=`${t}:${e}`;if("number"!=typeof l[n]||l[n]!==r){if(Object.values(l).includes(r))throw new Error(`can't register chainId ${r} for '${t}:${e}' because it's already registered for another chain id`);l[n]=r}},et=(t,e)=>{e&&(t+=`:${e}`);const r=l[t];if(!r)throw new Error(`chainId not found for ${t}`);return r},rt=t=>{const e=Q.idFromDID(t),r=Q.blockchainFromId(e),n=Q.networkIdFromId(e),i=l[`${r}:${n}`];if("number"!=typeof i)throw new Error(`chainId not found for ${r}:${n}`);return i},nt=({method:t,methodByte:e,blockchain:r,network:n,chainId:i,networkFlag:s})=>{Z(r),q(n),"number"==typeof e&&X(t,e),d[t]||(d[t]={}),"number"==typeof i&&tt(r,n,i);const o=`${r}:${n}`,a=d[t][o];if("number"!=typeof a||a!==s){if(Object.values(d[t]).includes(s))throw new Error(`DID network flag ${s.toString(2)} is already registered for the another network id for '${t}' method`);d[t][o]=s}};export{o as Blockchain,R as BytesHelper,l as ChainIds,P as Claim,C as ClaimOptions,s as Constants,Q as DID,F as DIDNetworkFlag,h as DidMethod,u as DidMethodByte,d as DidMethodNetwork,B as ElemBytes,M as ErrSlotOverflow,L as Flags,$ as Id,U as IdPosition,v as MerklizedFlag,V as MerklizedRootPosition,a as NetworkId,K as Param,W as Parser,k as SchemaHash,H as SlotName,O as StringUtils,A as SubjectFlag,G as buildDIDType,rt as chainIDfromDID,N as checkBigIntArrayInField,x as checkBigIntInField,I as encoder,Y as findBlockchainForDIDMethodByValue,j as findDIDMethodByValue,z as findNetworkIDForDIDMethodByValue,E as fromBigEndian,g as fromLittleEndian,T as genesisFromEthAddress,et as getChainId,p as getDateFromUnixTimestamp,m as getUint32,S as getUint64,b as getUnixTimestamp,D as idenState,J as initDIDParams,w as putUint32,_ as putUint64,Z as registerBlockchain,tt as registerChainId,X as registerDidMethod,nt as registerDidMethodNetwork,q as registerNetwork,y as toBigEndian,f as toLittleEndian}; //# sourceMappingURL=index.js.map