@polkadot/util#hexHasPrefix TypeScript Examples

The following examples show how to use @polkadot/util#hexHasPrefix. 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: util.ts    From crust-apps with Apache License 2.0 7 votes vote down vote up
// split is 65-byte signature into the r, s (combined) and recovery number (derived from v)
export function sigToParts (_signature: string): SignatureParts {
  const signature = hexHasPrefix(_signature) ? hexToU8a(_signature) : hexToU8a(hexAddPrefix(_signature));

  assert(signature.length === 65, `Invalid signature length, expected 65 found ${signature.length}`);

  let v = signature[64];

  if (v < 27) {
    v += 27;
  }

  const recovery = v - 27;

  assert(recovery === 0 || recovery === 1, 'Invalid signature v value');

  return {
    recovery,
    signature: u8aToBuffer(signature.slice(0, 64))
  };
}
Example #2
Source File: util.ts    From crust-apps with Apache License 2.0 7 votes vote down vote up
// recover an address from a signature JSON (as supplied by e.g. MyCrypto)
export function recoverFromJSON (signatureJson: string | null): RecoveredSignature {
  try {
    const { msg, sig } = JSON.parse(signatureJson || '{}') as Record<string, string>;

    if (!msg || !sig) {
      throw new Error('Invalid signature object');
    }

    const parts = sigToParts(sig);

    return {
      error: null,
      ethereumAddress: registry.createType('EthereumAddress', recoverAddress(hexHasPrefix(msg) ? hexToString(msg) : msg, parts)),
      signature: registry.createType('EcdsaSignature', u8aConcat(parts.signature, new Uint8Array([parts.recovery])))
    };
  } catch (error) {
    console.error(error);

    return {
      error: error as Error,
      ethereumAddress: null,
      signature: null
    };
  }
}