UNPKG

1.78 kBJavaScriptView Raw
1import { BN, bnToU8a, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
2import { blake2AsU8a } from '../blake2/asU8a.js';
3import { BN_LE_256_OPTS } from '../bn.js';
4const RE_NUMBER = /^\d+$/;
5const JUNCTION_ID_LEN = 32;
6export class DeriveJunction {
7 __internal__chainCode = new Uint8Array(32);
8 __internal__isHard = false;
9 static from(value) {
10 const result = new DeriveJunction();
11 const [code, isHard] = value.startsWith('/')
12 ? [value.substring(1), true]
13 : [value, false];
14 result.soft(RE_NUMBER.test(code)
15 ? new BN(code, 10)
16 : code);
17 return isHard
18 ? result.harden()
19 : result;
20 }
21 get chainCode() {
22 return this.__internal__chainCode;
23 }
24 get isHard() {
25 return this.__internal__isHard;
26 }
27 get isSoft() {
28 return !this.__internal__isHard;
29 }
30 hard(value) {
31 return this.soft(value).harden();
32 }
33 harden() {
34 this.__internal__isHard = true;
35 return this;
36 }
37 soft(value) {
38 if (isNumber(value) || isBn(value) || isBigInt(value)) {
39 return this.soft(bnToU8a(value, BN_LE_256_OPTS));
40 }
41 else if (isHex(value)) {
42 return this.soft(hexToU8a(value));
43 }
44 else if (isString(value)) {
45 return this.soft(compactAddLength(stringToU8a(value)));
46 }
47 else if (value.length > JUNCTION_ID_LEN) {
48 return this.soft(blake2AsU8a(value));
49 }
50 this.__internal__chainCode.fill(0);
51 this.__internal__chainCode.set(value, 0);
52 return this;
53 }
54 soften() {
55 this.__internal__isHard = false;
56 return this;
57 }
58}