Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement ADR-036 data signing #847

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .pnp.cjs

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

1 change: 1 addition & 0 deletions packages/stargate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@cosmjs/tendermint-rpc": "workspace:packages/tendermint-rpc",
"@cosmjs/utils": "workspace:packages/utils",
"cosmjs-types": "^0.3.0",
"fast-deep-equal": "^3.1.3",
"long": "^4.0.0",
"protobufjs": "~6.10.2",
"xstream": "^11.14.0"
Expand Down
106 changes: 106 additions & 0 deletions packages/stargate/src/signingstargateclient.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention,no-bitwise */
import { Secp256k1HdWallet } from "@cosmjs/amino";
import { toAscii } from "@cosmjs/encoding";
import { coin, coins, decodeTxRaw, DirectSecp256k1HdWallet, Registry } from "@cosmjs/proto-signing";
import { assert, sleep } from "@cosmjs/utils";
import { MsgSend } from "cosmjs-types/cosmos/bank/v1beta1/tx";
Expand Down Expand Up @@ -872,4 +873,109 @@ describe("SigningStargateClient", () => {
});
});
});

describe("experimentalAdr36Sign", () => {
it("works", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const client = await SigningStargateClient.offline(wallet);
const [firstAccount] = await wallet.getAccounts();

const data = toAscii("Hello, world");
const signed = await client.experimentalAdr36Sign(firstAccount.address, data);
expect(signed).toEqual({
msg: [
{
type: "sign/MsgSignData",
value: {
signer: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6",
data: "SGVsbG8sIHdvcmxk", // echo -n "Hello, world" | base64
},
},
],
fee: {
amount: [],
gas: "0",
},
signatures: [
{
pub_key: {
type: "tendermint/PubKeySecp256k1",
value: "A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ",
},
signature:
"x9jjSFv8/n1F8gOSRjddakYDbvroQm8ZoDWht/Imc1t5xUW49+Xaq7gwcsE+LCpqYoTBxnaXLg/xgJjYymCWvw==",
},
],
memo: "",
});
});

it("works for multiple datas", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const client = await SigningStargateClient.offline(wallet);
const [firstAccount] = await wallet.getAccounts();

const data1 = toAscii("Hello");
const data2 = toAscii("World");
const signed = await client.experimentalAdr36Sign(firstAccount.address, [data1, data2]);
expect(signed).toEqual({
msg: [
{
type: "sign/MsgSignData",
value: {
signer: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6",
data: "SGVsbG8=", // echo -n "Hello" | base64
},
},
{
type: "sign/MsgSignData",
value: {
signer: "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6",
data: "V29ybGQ=", // echo -n "World" | base64
},
},
],
fee: {
amount: [],
gas: "0",
},
signatures: [
{
pub_key: {
type: "tendermint/PubKeySecp256k1",
value: "A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ",
},
signature:
"KvN9FM/WSfsJERv4PS91Ey7SUrnVJ/XHpHmMDh0sC94Niz2JLfF9KKE1QMfL5KtVFSRdMkJJsMtgl+aCaUyOCw==",
},
],
memo: "",
});
});
});

describe("experimentalAdr36Verify", () => {
it("works", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const client = await SigningStargateClient.offline(wallet);
const [firstAccount] = await wallet.getAccounts();

const data = toAscii("Hello, world");
const signed = await client.experimentalAdr36Sign(firstAccount.address, data);
const ok = await SigningStargateClient.experimentalAdr36Verify(signed);
expect(ok).toEqual(true);
});

it("works with multiple datas", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(faucet.mnemonic);
const client = await SigningStargateClient.offline(wallet);
const [firstAccount] = await wallet.getAccounts();

const data1 = toAscii("Hello");
const data2 = toAscii("World");
const signed = await client.experimentalAdr36Sign(firstAccount.address, [data1, data2]);
const ok = await SigningStargateClient.experimentalAdr36Verify(signed);
expect(ok).toEqual(true);
});
});
});
128 changes: 125 additions & 3 deletions packages/stargate/src/signingstargateclient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { encodeSecp256k1Pubkey, makeSignDoc as makeSignDocAmino, StdFee } from "@cosmjs/amino";
import { fromBase64 } from "@cosmjs/encoding";
import {
AminoMsg,
encodeSecp256k1Pubkey,
isSecp256k1Pubkey,
makeSignDoc as makeSignDocAmino,
makeStdTx,
rawSecp256k1PubkeyToRawAddress,
serializeSignDoc,
StdFee,
StdTx,
} from "@cosmjs/amino";
import { Secp256k1, Secp256k1Signature, sha256 } from "@cosmjs/crypto";
import { Bech32, fromBase64, toBase64 } from "@cosmjs/encoding";
import { Int53, Uint53 } from "@cosmjs/math";
import {
EncodeObject,
Expand All @@ -13,7 +24,7 @@ import {
TxBodyEncodeObject,
} from "@cosmjs/proto-signing";
import { Tendermint34Client } from "@cosmjs/tendermint-rpc";
import { assert, assertDefined } from "@cosmjs/utils";
import { arrayContentEquals, assert, assertDefined, isNonNullObject } from "@cosmjs/utils";
import { MsgMultiSend } from "cosmjs-types/cosmos/bank/v1beta1/tx";
import { Coin } from "cosmjs-types/cosmos/base/v1beta1/coin";
import {
Expand Down Expand Up @@ -58,6 +69,7 @@ import {
MsgConnectionOpenInit,
MsgConnectionOpenTry,
} from "cosmjs-types/ibc/core/connection/v1/tx";
import equals from "fast-deep-equal";
import Long from "long";

import { AminoTypes } from "./aminotypes";
Expand Down Expand Up @@ -110,6 +122,28 @@ function createDefaultRegistry(): Registry {
return new Registry(defaultRegistryTypes);
}

/**
* See ADR-036
*/
interface MsgSignData extends AminoMsg {
readonly type: "sign/MsgSignData";
readonly value: {
/** Bech32 account address */
signer: string;
/** Base64 encoded data */
data: string;
};
}

export function isMsgSignData(msg: AminoMsg): msg is MsgSignData {
const castedMsg = msg as MsgSignData;
if (castedMsg.type !== "sign/MsgSignData") return false;
if (!isNonNullObject(castedMsg.value)) return false;
if (typeof castedMsg.value.signer !== "string") return false;
if (typeof castedMsg.value.data !== "string") return false;
return true;
}

/**
* Signing information for a single signer that is not included in the transaction.
*
Expand Down Expand Up @@ -359,6 +393,94 @@ export class SigningStargateClient extends StargateClient {
: this.signAmino(signerAddress, messages, fee, memo, signerData);
}

public async experimentalAdr36Sign(signerAddress: string, data: Uint8Array | Uint8Array[]): Promise<StdTx> {
const accountNumber = 0;
const sequence = 0;
const chainId = "";
const fee: StdFee = {
gas: "0",
amount: [],
};
const memo = "";

const datas = Array.isArray(data) ? data : [data];

const msgs: MsgSignData[] = datas.map(
(d): MsgSignData => ({
type: "sign/MsgSignData",
value: {
signer: signerAddress,
data: toBase64(d),
},
}),
);

assert(!isOfflineDirectSigner(this.signer));
const accountFromSigner = (await this.signer.getAccounts()).find(
(account) => account.address === signerAddress,
);
if (!accountFromSigner) {
throw new Error("Failed to retrieve account from signer");
}
const signDoc = makeSignDocAmino(msgs, fee, chainId, memo, accountNumber, sequence);
const { signature, signed } = await this.signer.signAmino(signerAddress, signDoc);
if (!equals(signDoc, signed)) {
throw new Error(
"The signed document differs from the signing instruction. This is not supported for ADR-036.",
);
}

return makeStdTx(signDoc, signature);
}

public static async experimentalAdr36Verify(signed: StdTx): Promise<boolean> {
// Restrictions from ADR-036
if (signed.memo !== "") throw new Error("Memo must be empty.");
if (signed.fee.gas !== "0") throw new Error("Fee gas must 0.");
if (signed.fee.amount.length !== 0) throw new Error("Fee amount must be an empty array.");

const accountNumber = 0;
const sequence = 0;
const chainId = "";

// Check `msg` array
const signedMessages = signed.msg;
if (!signedMessages.every(isMsgSignData)) {
throw new Error(`Found message that is not the expected type.`);
}
if (signedMessages.length === 0) {
throw new Error("No message found. Without messages we cannot determine the signer address.");
}
// TODO: restrict number of messages?

const signatures = signed.signatures;
if (signatures.length !== 1) throw new Error("Must have exactly one signature to be supported.");
const signature = signatures[0];
if (!isSecp256k1Pubkey(signature.pub_key)) {
throw new Error("Only secp256k1 signatures are supported.");
}

const signBytes = serializeSignDoc(
makeSignDocAmino(signed.msg, signed.fee, chainId, signed.memo, accountNumber, sequence),
);
const prehashed = sha256(signBytes);

const secpSignature = Secp256k1Signature.fromFixedLength(fromBase64(signature.signature));
const rawSecp256k1Pubkey = fromBase64(signature.pub_key.value);
const rawSignerAddress = rawSecp256k1PubkeyToRawAddress(rawSecp256k1Pubkey);

if (
signedMessages.some(
(msg) => !arrayContentEquals(Bech32.decode(msg.value.signer).data, rawSignerAddress),
)
) {
throw new Error("Found mismatch between signer in message and public key");
}

const ok = await Secp256k1.verifySignature(secpSignature, prehashed, rawSecp256k1Pubkey);
return ok;
}

private async signAmino(
signerAddress: string,
messages: readonly EncodeObject[],
Expand Down
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,7 @@ __metadata:
eslint-plugin-prettier: ^3.4.0
eslint-plugin-simple-import-sort: ^7.0.0
esm: ^3.2.25
fast-deep-equal: ^3.1.3
glob: ^7.1.6
jasmine: ^3.8
jasmine-core: ^3.7.1
Expand Down