@polkadot/util-crypto#blake2AsU8a TypeScript Examples

The following examples show how to use @polkadot/util-crypto#blake2AsU8a. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Signer.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
  }
Example #2
Source File: index.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('bodhi', () => {
  it('should export the Provider', () => {
    expect(Provider).to.not.be.undefined;
  });

  it('default evm address', () => {
    const accountid = decodeAddress('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY');

    const encode = u8aConcat('evm:', accountid);

    expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).to.equal('0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9');
  });
});
Example #3
Source File: address.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
computeDefaultEvmAddress = (substrateAddress: HexString | string | Uint8Array): string => {
  if (!isSubstrateAddress) {
    return logger.throwArgumentError('invalid substrate address', 'address', substrateAddress);
  }

  const publicKey = decodeAddress(substrateAddress);

  const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

  if (isStartWithEvm) {
    return getAddress(u8aToHex(publicKey.slice(4, 24)));
  }

  return getAddress(u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20)));
}
Example #4
Source File: utils.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
blake2 = (value: Uint8Array): Uint8Array => blake2AsU8a(value, 512)
Example #5
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createInfo (value: string): string[] {
  const hash = {
    hash: blake2AsU8a(value),
    index: 0
  };
  const result = [getIndex(backgrounds, hash) as string];

  getIndex(sets, hash).forEach((section): void => {
    result.push(getIndex(section, hash) as string);
  });

  return result;
}
Example #6
Source File: QrSigner.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      // limit size of the transaction
      const isQrHashed = (payload.method.length > 5000);
      const wrapper = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version });
      const qrPayload = isQrHashed
        ? blake2AsU8a(wrapper.toU8a(true))
        : wrapper.toU8a();

      this.#setState({
        isQrHashed,
        qrAddress: payload.address,
        qrPayload,
        qrReject: reject,
        qrResolve: resolve
      });
    });
  }
Example #7
Source File: Signer.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @returns The default EVM address generated for the signer's substrate address
   */
  computeDefaultEvmAddress(): string {
    const address = this._substrateAddress;
    const publicKey = decodeAddress(address);

    const isStartWithEvm = u8aEq('evm:', publicKey.slice(0, 4));

    if (isStartWithEvm) {
      return getAddress(u8aToHex(publicKey.slice(4, 24)));
    }

    return getAddress(
      u8aToHex(blake2AsU8a(u8aConcat('evm:', publicKey), 256).slice(0, 20))
    );
  }
Example #8
Source File: index.spec.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
describe('evm-provider', () => {
  it('should export the Provider', () => {
    expect(Provider).toBeDefined();
  });

  it('default evm address', () => {
    const accountid = decodeAddress(
      '5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY'
    );

    const encode = u8aConcat('evm:', accountid);

    expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).toEqual(
      '0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9'
    );
  });
});
Example #9
Source File: QrSigner.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
public async signPayload(payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve, reject): void => {
      // limit size of the transaction
      // eslint-disable-next-line no-magic-numbers
      const isQrHashed = payload.method.length > 5000;
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const wrapper = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version });
      const qrPayload = isQrHashed ? blake2AsU8a(wrapper.toU8a(true)) : wrapper.toU8a();

      this.#setState({
        isQrHashed,
        qrAddress: payload.address,
        qrPayload,
        qrReject: reject,
        qrResolve: resolve,
      });
    });
  }
Example #10
Source File: test-assets-sufficients.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
async function mockAssetBalance(
  context,
  assetBalance,
  assetDetails,
  sudoAccount,
  assetId,
  account,
  is_sufficient
) {
  // Register the asset
  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.assetManager.registerForeignAsset(
        sourceLocationRelayAssetType,
        relayAssetMetadata,
        new BN(1),
        is_sufficient
      )
    )
    .signAndSend(sudoAccount);
  await context.createBlock();

  let assets = (
    (await context.polkadotApi.query.assetManager.assetIdType(assetId)) as any
  ).toJSON();
  // make sure we created it
  expect(assets["xcm"]["parents"]).to.equal(1);

  // Get keys to modify balance
  let module = xxhashAsU8a(new TextEncoder().encode("Assets"), 128);
  let account_key = xxhashAsU8a(new TextEncoder().encode("Account"), 128);
  let blake2concatAssetId = new Uint8Array([
    ...blake2AsU8a(assetId.toU8a(), 128),
    ...assetId.toU8a(),
  ]);

  let blake2concatAccount = new Uint8Array([
    ...blake2AsU8a(hexToU8a(account), 128),
    ...hexToU8a(account),
  ]);
  let overallAccountKey = new Uint8Array([
    ...module,
    ...account_key,
    ...blake2concatAssetId,
    ...blake2concatAccount,
  ]);

  // Get keys to modify total supply
  let assetKey = xxhashAsU8a(new TextEncoder().encode("Asset"), 128);
  let overallAssetKey = new Uint8Array([...module, ...assetKey, ...blake2concatAssetId]);
  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.system.setStorage([
        [u8aToHex(overallAccountKey), u8aToHex(assetBalance.toU8a())],
        [u8aToHex(overallAssetKey), u8aToHex(assetDetails.toU8a())],
      ])
    )
    .signAndSend(sudoAccount);
  await context.createBlock();
  return;
}
Example #11
Source File: test-precompile-assets-erc20.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
export async function mockAssetBalance(
  context,
  assetBalance,
  assetDetails,
  sudoAccount,
  assetId,
  account
) {
  // Register the asset
  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.assetManager.registerForeignAsset(
        sourceLocationRelayAssetType,
        relayAssetMetadata,
        new BN(1),
        true
      )
    )
    .signAndSend(sudoAccount);
  await context.createBlock();

  let assets = (
    (await context.polkadotApi.query.assetManager.assetIdType(assetId)) as any
  ).toJSON();
  // make sure we created it
  expect(assets["xcm"]["parents"]).to.equal(1);

  // Get keys to modify balance
  let module = xxhashAsU8a(new TextEncoder().encode("Assets"), 128);
  let account_key = xxhashAsU8a(new TextEncoder().encode("Account"), 128);
  let blake2concatAssetId = new Uint8Array([
    ...blake2AsU8a(assetId.toU8a(), 128),
    ...assetId.toU8a(),
  ]);

  let blake2concatAccount = new Uint8Array([
    ...blake2AsU8a(hexToU8a(account), 128),
    ...hexToU8a(account),
  ]);
  let overallAccountKey = new Uint8Array([
    ...module,
    ...account_key,
    ...blake2concatAssetId,
    ...blake2concatAccount,
  ]);

  // Get keys to modify total supply
  let assetKey = xxhashAsU8a(new TextEncoder().encode("Asset"), 128);
  let overallAssetKey = new Uint8Array([...module, ...assetKey, ...blake2concatAssetId]);
  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.system.setStorage([
        [u8aToHex(overallAccountKey), u8aToHex(assetBalance.toU8a())],
        [u8aToHex(overallAssetKey), u8aToHex(assetDetails.toU8a())],
      ])
    )
    .signAndSend(sudoAccount);
  await context.createBlock();
  return;
}
Example #12
Source File: test-precompile-xcm-transactor.ts    From moonbeam with GNU General Public License v3.0 5 votes vote down vote up
async function mockAssetBalance(context, assetBalance, assetDetails, sudoAccount, assetId) {
  // Register the asset
  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.assetManager.registerForeignAsset(
        sourceLocationRelayAssetType,
        relayAssetMetadata,
        new BN(1),
        true
      )
    )
    .signAndSend(sudoAccount);
  await context.createBlock();

  let assets = (
    (await context.polkadotApi.query.assetManager.assetIdType(assetId)) as any
  ).toJSON();
  // make sure we created it
  expect(assets["xcm"]["parents"]).to.equal(1);

  // Get keys to modify balance
  let module = xxhashAsU8a(new TextEncoder().encode("Assets"), 128);
  let account_key = xxhashAsU8a(new TextEncoder().encode("Account"), 128);
  let blake2concatAssetId = new Uint8Array([
    ...blake2AsU8a(assetId.toU8a(), 128),
    ...assetId.toU8a(),
  ]);
  let blake2concatAccount = new Uint8Array([
    ...blake2AsU8a(hexToU8a(ALITH), 128),
    ...hexToU8a(ALITH),
  ]);
  let overallAccountKey = new Uint8Array([
    ...module,
    ...account_key,
    ...blake2concatAssetId,
    ...blake2concatAccount,
  ]);

  // Get keys to modify total supply
  let assetKey = xxhashAsU8a(new TextEncoder().encode("Asset"), 128);
  let overallAssetKey = new Uint8Array([...module, ...assetKey, ...blake2concatAssetId]);

  await context.polkadotApi.tx.sudo
    .sudo(
      context.polkadotApi.tx.system.setStorage([
        [u8aToHex(overallAccountKey), u8aToHex(assetBalance.toU8a())],
        [u8aToHex(overallAssetKey), u8aToHex(assetDetails.toU8a())],
      ])
    )
    .signAndSend(sudoAccount);
  await context.createBlock();
  return;
}
Example #13
Source File: generate.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
export function generateProgramId(code: Buffer | Uint8Array, salt: string | Hex | Uint8Array): Hex {
  const codeHashU8a = blake2AsU8a(code, 256);
  const saltU8a = CreateType.create('Vec<u8>', salt).toU8a().slice(1);
  const id = new Uint8Array(codeHashU8a.byteLength + saltU8a.byteLength);
  id.set(codeHashU8a);
  id.set(saltU8a, codeHashU8a.byteLength);
  return blake2AsHex(id, 256);
}
Example #14
Source File: customHashers.ts    From parity-bridges-ui with GNU General Public License v3.0 5 votes vote down vote up
function blake2Keccak256Hasher(data: Uint8Array) {
  return u8aConcat(blake2AsU8a(data), keccakAsU8a(data));
}
Example #15
Source File: QrSigner.ts    From sdk with Apache License 2.0 5 votes vote down vote up
export function makeTx(api: ApiPromise, txInfo: any, paramList: any[], ss58: number) {
  return new Promise((resolve) => {
    const signer = txInfo.proxy ? encodeAddress(hexToU8a(txInfo.proxy.pubKey), ss58) : txInfo.sender.address;
    api.derive.tx
      .signingInfo(signer)
      .then(async ({ header, mortalLength, nonce }) => {
        let tx: SubmittableExtrinsic<"promise">;
        // wrap tx with council.propose for treasury propose
        if (txInfo.txName == "treasury.approveProposal") {
          tx = await gov.makeTreasuryProposalSubmission(api, paramList[0], false);
        } else if (txInfo.txName == "treasury.rejectProposal") {
          tx = await gov.makeTreasuryProposalSubmission(api, paramList[0], true);
        } else {
          tx = api.tx[txInfo.module][txInfo.call](...paramList);
        }
        // wrap tx with recovery.asRecovered for proxy tx
        if (txInfo.proxy) {
          tx = api.tx.recovery.asRecovered(txInfo.sender.address, tx);
        }
        const signerPayload = api.registry.createType("SignerPayload", {
          address: signer,
          blockHash: header.hash,
          blockNumber: header ? header.number : 0,
          era: api.registry.createType("ExtrinsicEra", {
            current: header.number,
            period: mortalLength,
          }),
          genesisHash: api.genesisHash,
          method: tx.method,
          nonce,
          signedExtensions: ["CheckNonce"],
          tip: txInfo.tip,
          runtimeVersion: {
            specVersion: api.runtimeVersion.specVersion,
            transactionVersion: api.runtimeVersion.transactionVersion,
          },
          version: api.extrinsicVersion,
        });
        const payload = signerPayload.toPayload();

        // limit size of the transaction
        const qrIsHashed = payload.method.length > 5000;
        const wrapper = api.registry.createType("ExtrinsicPayload", payload, {
          version: payload.version,
        });
        const qrPayload = qrIsHashed ? blake2AsU8a(wrapper.toU8a(true)) : wrapper.toU8a();
        // cache this submittableExtrinsic
        submittable = {
          tx,
          payload: signerPayload.toPayload(),
        };
        // submittable.tx = tx;
        // submittable.payload = signerPayload.toPayload();
        resolve({
          qrAddress: payload.address,
          qrIsHashed,
          qrPayload: _createFrames(_createSignPayload(payload.address, qrIsHashed ? CMD_HASH : CMD_MORTAL, qrPayload, api.genesisHash))[0],
        });
      })
      .catch((err) => resolve({ error: err.message }));
  });
}