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 signMessage method #1210

Closed
Closed
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
5 changes: 5 additions & 0 deletions .changeset/nice-cheetahs-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@near-js/wallet-account": patch
---

Fix requestSignIn method
5 changes: 3 additions & 2 deletions packages/accounts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
"bn.js": "5.2.1",
"borsh": "1.0.0",
"depd": "^2.0.0",
"lru_map": "^0.4.1",
"near-abi": "0.1.1"
"near-abi": "0.1.1",
"js-sha256": "0.9.0",
"lru_map": "^0.4.1"
},
"devDependencies": {
"@near-js/keystores": "workspace:*",
Expand Down
41 changes: 41 additions & 0 deletions packages/accounts/src/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
SignedDelegate,
SignedTransaction,
stringifyJsonOrBytes,
SCHEMA,
} from '@near-js/transactions';
import {
PositionalArgsError,
Expand All @@ -35,8 +36,10 @@ import {
printTxOutcomeLogsAndFailures,
} from '@near-js/utils';
import BN from 'bn.js';
import { serialize } from 'borsh';

import { Connection } from './connection';
import { PREFIX_TAG } from './constants';

const {
addKey,
Expand Down Expand Up @@ -154,6 +157,20 @@ interface SignedDelegateOptions {
receiverId: string;
}


interface SignMessageParams {
message: string ; // The message that wants to be transmitted.
recipient: string; // The recipient to whom the message is destined (e.g. "alice.near" or "myapp.com").
nonce: Uint8Array[]; // A nonce that uniquely identifies this instance of the message, denoted as a 32 bytes array (a fixed `Buffer` in JS/TS).
callbackUrl?: string; // Optional, applicable to browser wallets (e.g. MyNearWallet). The URL to call after the signing process. Defaults to `window.location.href`.
}

interface SignedMessage {
accountId: string; // The account name to which the publicKey corresponds as plain text (e.g. "alice.near")
publicKey: string; // The public counterpart of the key used to sign, expressed as a string with format "<key-type>:<base58-key-bytes>" (e.g. "ed25519:6TupyNrcHGTt5XRLmHTc2KGaiSbjhQi1KHtCXTgbcr4Y")
signature: string; // The base64 representation of the signature.
}

function parseJsonFromRawResponse(response: Uint8Array): any {
return JSON.parse(Buffer.from(response).toString());
}
Expand Down Expand Up @@ -707,4 +724,28 @@ export class Account {
total: summary.total.toString(),
};
}

/**
* @param message The message that wants to be transmitted.
* @param recipient The recipient to whom the message is destined (e.g. "alice.near" or "myapp.com").
* @param nonce A nonce that uniquely identifies this instance of the message, denoted as a 32 bytes array (a fixed `Buffer` in JS/TS).
* @param callbackUrl Optional, applicable to browser wallets (e.g. MyNearWallet). The URL to call after the signing process. Defaults to `window.location.href`.
*/
async signMessage({ message, recipient, nonce, callbackUrl }: SignMessageParams): Promise<SignedMessage> {
// Check the nonce is a 32bytes array
if (nonce.length != 32) { throw Error('Expected nonce to be a 32 bytes buffer'); }

const borshPayload = serialize(SCHEMA.SignMessagePayload, {
tag: PREFIX_TAG,
message,
nonce,
recipient,
callbackUrl
});
const { signature } = await this.connection.signer.signMessage(borshPayload, this.accountId, this.connection.networkId);
const encoded: string = Buffer.from(signature).toString('base64');
const publicKey = (await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId)).toString();

return { accountId: this.accountId, publicKey, signature: encoded };
}
}
2 changes: 2 additions & 0 deletions packages/accounts/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ export const MULTISIG_GAS = new BN('100000000000000');
export const MULTISIG_DEPOSIT = new BN('0');
export const MULTISIG_CHANGE_METHODS = ['add_request', 'add_request_and_confirm', 'delete_request', 'confirm'];
export const MULTISIG_CONFIRM_METHODS = ['confirm'];

export const PREFIX_TAG = 2147484061; // 2**31 + 413
28 changes: 28 additions & 0 deletions packages/accounts/test/account.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,31 @@ describe('with deploy contract', () => {
}
});
});

describe('sign message', () => {
const message = testUtils.generateUniqueString('message');
const recipient = testUtils.generateUniqueString('recipient');
const callbackUrl = 'http://example.com/callback';
let account;

beforeAll(async () => {
const newAccount = await testUtils.createAccount(nearjs);
account = new Account(nearjs.connection, newAccount.accountId);
});

test('verify signature', async () => {
const nonce = new Uint8Array(32);
const { publicKey, signature } = await account.signMessage({ message, recipient, nonce, callbackUrl });
const verified = testUtils.verifySignature({ message, recipient, nonce, callbackUrl, publicKey, signature });
expect(verified).toEqual(true);
});

test('sign with 31 bytes nonce', async () => {
const nonce = new Uint8Array(31);
try {
await account.signMessage({ message, recipient, nonce, callbackUrl });
} catch (e) {
expect(e.message).toEqual('Expected nonce to be a 32 bytes buffer');
}
});
});
21 changes: 20 additions & 1 deletion packages/accounts/test/test-utils.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const { KeyPair } = require('@near-js/crypto');
const { KeyPair, PublicKey } = require('@near-js/crypto');
const { InMemoryKeyStore } = require('@near-js/keystores');
const { SCHEMA } = require( '@near-js/transactions' );
const BN = require('bn.js');
const fs = require('fs').promises;

const { serialize } = require('borsh');
const { sha256 } = require('js-sha256');
const path = require('path');

const { Account, AccountMultisig, Contract, Connection, LocalAccountCreator } = require('../lib');
const { PREFIX_TAG } = require( '../lib/constants' );

const networkId = 'unittest';

Expand Down Expand Up @@ -150,6 +155,19 @@ function waitFor(fn) {
return _waitFor();
}

function verifySignature({ message, nonce, recipient, callbackUrl, publicKey, signature }) {
const borshPayload = serialize(SCHEMA.SignMessagePayload, {
tag: PREFIX_TAG,
message,
nonce,
recipient,
callbackUrl
});
const toSign = Uint8Array.from(sha256.array(borshPayload));
const pk = PublicKey.from(publicKey);
return pk.verify(toSign, Buffer.from(signature, 'base64'));
}

module.exports = {
setUpTestConnection,
networkId,
Expand All @@ -166,4 +184,5 @@ module.exports = {
GUESTBOOK_WASM_PATH,
sleep,
waitFor,
verifySignature
};
9 changes: 9 additions & 0 deletions packages/transactions/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,13 @@ export const SCHEMA = new class BorshSchema {
signature: this.Signature,
}
};
SignMessagePayload: Schema = {
struct: {
tag: 'u32', // Always the same tag: 2**31 + 413
message: 'string',
nonce: { array: { type: 'u8', len: 32 } },
recipient: 'string',
callbackUrl: { option: 'string' }
}
};
};
2 changes: 2 additions & 0 deletions packages/wallet-account/src/wallet_account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,11 @@ export class WalletConnection {
await contractAccount.state();

newUrl.searchParams.set('contract_id', contractId);

const accessKey = KeyPair.fromRandom('ed25519');
newUrl.searchParams.set('public_key', accessKey.getPublicKey().toString());
await this._keyStore.setKey(this._networkId, PENDING_ACCESS_KEY_PREFIX + accessKey.getPublicKey(), accessKey);

}

if (methodNames) {
Expand Down
32 changes: 26 additions & 6 deletions pnpm-lock.yaml

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

Loading