Skip to content

Commit

Permalink
Merge pull request #81 from terra-money/ST-1308-sign-arbitray-impleme…
Browse files Browse the repository at this point in the history
…ntation

Implement verifyArbitrary function
  • Loading branch information
alecande11 authored Feb 12, 2024
2 parents d54c6e0 + 22d5184 commit ec383ff
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@terra-money/feather.js",
"version": "2.0.3",
"version": "2.0.4",
"description": "The JavaScript SDK for Terra and Feather chains",
"license": "MIT",
"author": "Terraform Labs, PTE.",
Expand Down
64 changes: 64 additions & 0 deletions src/extension/verifyArbitrary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { bech32 } from 'bech32';
import { AccAddress, PublicKey, Tx } from '../core';
import secp256k1 from 'secp256k1';
import keccak256 from 'keccak256';
import { SHA256, Word32Array } from 'jscrypto';
import { prepareSignBytes } from '../util/json';

export default function verifyArbitrary(
signerAddress: AccAddress,
data: string,
signResult: {
pub_key: PublicKey.Data;
signature: string;
}
) {
if (Buffer.from(data, 'base64').toString('base64') !== data)
throw new Error('Data must be a base64 encoded string');

const prefix = bech32.decode(signerAddress).prefix;

if (
signerAddress !== PublicKey.fromData(signResult.pub_key).address(prefix)
) {
// provided address does not match the pubkey used for the signature
return false;
}

const tx = Buffer.from(
JSON.stringify(
prepareSignBytes({
chain_id: '',
account_number: '0',
sequence: '0',
fee: {
gas: '0',
amount: [],
},
msgs: [
{
type: 'sign/MsgSignData',
value: {
signer: signerAddress,
data,
},
},
],
memo: '',
})
)
);

const hash =
signResult.pub_key['@type'] ===
'/injective.crypto.v1beta1.ethsecp256k1.PubKey'
? keccak256(tx)
: Buffer.from(SHA256.hash(new Word32Array(tx)).toString(), 'hex');

return secp256k1.ecdsaVerify(
Buffer.from(signResult.signature, 'base64'),
hash,
// @ts-expect-error
Buffer.from(signResult.pub_key.key as string, 'base64')
);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from './core';
export * from './key';
export * from './client';
export * from './extension';
export * from './extension/verifyArbitrary';
export * from './util';

0 comments on commit ec383ff

Please sign in to comment.