Add token bridge client for eth and solana

Change-Id: I0f9af0ffc606aed58579f167fadf80d1964360c8
This commit is contained in:
Hendrik Hofstadt 2021-08-06 14:04:16 +02:00
parent 8cee72ba9c
commit bedc96d887
11 changed files with 46368 additions and 6 deletions

2
clients/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
contracts
ethers-contracts

View File

@ -0,0 +1,324 @@
import yargs from "yargs";
const {hideBin} = require('yargs/helpers')
import * as bridge from "bridge";
import * as token_bridge from "token-bridge";
import * as web3s from '@solana/web3.js';
import {PublicKey, TransactionInstruction, AccountMeta, Keypair, Connection} from "@solana/web3.js";
import * as ethers from "ethers";
import * as elliptic from "elliptic";
import {solidityKeccak256} from "ethers/lib/utils";
import {BridgeImplementation__factory} from "./src/ethers-contracts";
const signAndEncodeVM = function (
timestamp,
nonce,
emitterChainId,
emitterAddress,
sequence,
data,
signers,
guardianSetIndex,
consistencyLevel
) {
const body = [
ethers.utils.defaultAbiCoder.encode(["uint32"], [timestamp]).substring(2 + (64 - 8)),
ethers.utils.defaultAbiCoder.encode(["uint32"], [nonce]).substring(2 + (64 - 8)),
ethers.utils.defaultAbiCoder.encode(["uint16"], [emitterChainId]).substring(2 + (64 - 4)),
ethers.utils.defaultAbiCoder.encode(["bytes32"], [emitterAddress]).substring(2),
ethers.utils.defaultAbiCoder.encode(["uint64"], [sequence]).substring(2 + (64 - 16)),
ethers.utils.defaultAbiCoder.encode(["uint8"], [consistencyLevel]).substring(2 + (64 - 2)),
data.substr(2)
]
const hash = solidityKeccak256(["bytes"], [solidityKeccak256(["bytes"], ["0x" + body.join("")])])
let signatures = "";
for (let i in signers) {
const ec = new elliptic.ec("secp256k1");
const key = ec.keyFromPrivate(signers[i]);
const signature = key.sign(Buffer.from(hash.substr(2), "hex"), {canonical: true});
const packSig = [
ethers.utils.defaultAbiCoder.encode(["uint8"], [i]).substring(2 + (64 - 2)),
zeroPadBytes(signature.r.toString(16), 32),
zeroPadBytes(signature.s.toString(16), 32),
ethers.utils.defaultAbiCoder.encode(["uint8"], [signature.recoveryParam]).substr(2 + (64 - 2)),
]
signatures += packSig.join("")
}
const vm = [
ethers.utils.defaultAbiCoder.encode(["uint8"], [1]).substring(2 + (64 - 2)),
ethers.utils.defaultAbiCoder.encode(["uint32"], [guardianSetIndex]).substring(2 + (64 - 8)),
ethers.utils.defaultAbiCoder.encode(["uint8"], [signers.length]).substring(2 + (64 - 2)),
signatures,
body.join("")
].join("");
return vm
}
function zeroPadBytes(value, length) {
while (value.length < 2 * length) {
value = "0" + value;
}
return value;
}
yargs(hideBin(process.argv))
.command('generate_register_chain_vaa [chain_id] [contract_address]', 'create a VAA to register a chain (debug-only)', (yargs) => {
return yargs
.positional('chain_id', {
describe: 'chain id to register',
type: "number",
required: true
})
.positional('contract_address', {
describe: 'contract to register',
type: "string",
required: true
})
}, async (argv: any) => {
let data = [
"0x",
"000000000000000000000000000000000000000000546f6b656e427269646765", // Token Bridge header
"01",
"0000",
ethers.utils.defaultAbiCoder.encode(["uint16"], [argv.chain_id]).substring(2 + (64 - 4)),
ethers.utils.defaultAbiCoder.encode(["bytes32"], [argv.contract_address]).substring(2),
].join('')
const vm = signAndEncodeVM(
1,
1,
1,
"0x0000000000000000000000000000000000000000000000000000000000000004",
0,
data,
[
"cfb12303a19cde580bb4dd771639b0d26bc68353645571a8cff516ab2ee113a0"
],
0,
0
);
console.log(vm)
})
.command('solana execute_governance_vaa [vaa]', 'execute a governance VAA on Solana', (yargs) => {
return yargs
.positional('vaa', {
describe: 'vaa to post',
type: "string",
required: true
})
.option('rpc', {
alias: 'u',
type: 'string',
description: 'URL of the Solana RPC',
default: "http://localhost:8899"
})
.option('bridge', {
alias: 'b',
type: 'string',
description: 'Bridge address',
default: "Bridge1p5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o"
})
.option('token_bridge', {
alias: 't',
type: 'string',
description: 'Token Bridge address',
default: "B6RHG3mfcckmrYN1UhmJzyS1XX3fZKbkeUcpJe9Sy3FE"
})
}, async (argv: any) => {
let connection = setupConnection(argv);
let bridge_id = new PublicKey(argv.bridge);
let token_bridge_id = new PublicKey(argv.token_bridge);
// Generate a new random public key
let from = web3s.Keypair.generate();
let airdropSignature = await connection.requestAirdrop(
from.publicKey,
web3s.LAMPORTS_PER_SOL,
);
await connection.confirmTransaction(airdropSignature);
let vaa = Buffer.from(argv.vaa, "hex");
await post_vaa(connection, bridge_id, from, vaa);
let parsed_vaa = await bridge.parse_vaa(vaa);
let ix: TransactionInstruction;
switch (parsed_vaa.payload[32]) {
case 1:
console.log("Registering chain")
ix = token_bridge.register_chain_ix(token_bridge_id.toString(), bridge_id.toString(), from.publicKey.toString(), vaa);
break
case 2:
console.log("Upgrading contract")
ix = token_bridge.upgrade_contract_ix(token_bridge_id.toString(), bridge_id.toString(), from.publicKey.toString(), from.publicKey.toString(), vaa);
break
default:
throw new Error("unknown governance action")
}
let transaction = new web3s.Transaction().add(ixFromRust(ix));
// Sign transaction, broadcast, and confirm
let signature = await web3s.sendAndConfirmTransaction(
connection,
transaction,
[from],
{
skipPreflight: true
}
);
console.log('SIGNATURE', signature);
})
.command('eth execute_governance_vaa [vaa]', 'execute a governance VAA on Solana', (yargs) => {
return yargs
.positional('vaa', {
describe: 'vaa to post',
type: "string",
required: true
})
.option('rpc', {
alias: 'u',
type: 'string',
description: 'URL of the ETH RPC',
default: "http://localhost:8545"
})
.option('token_bridge', {
alias: 't',
type: 'string',
description: 'Token Bridge address',
default: "0xe982e462b094850f12af94d21d470e21be9d0e9c"
})
.option('key', {
alias: 'k',
type: 'string',
description: 'Private key of the wallet',
default: "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
})
}, async (argv: any) => {
let provider = new ethers.providers.JsonRpcProvider(argv.rpc)
let signer = new ethers.Wallet(argv.key, provider)
let t = new BridgeImplementation__factory(signer);
let tb = t.attach(argv.token_bridge);
let vaa = Buffer.from(argv.vaa, "hex");
let parsed_vaa = await bridge.parse_vaa(vaa);
switch (parsed_vaa.payload[32]) {
case 1:
console.log("Registering chain")
console.log("Hash: " + (await tb.registerChain(vaa)).hash)
break
case 2:
console.log("Upgrading contract")
console.log("Hash: " + (await tb.upgrade(vaa)).hash)
break
default:
throw new Error("unknown governance action")
}
})
.argv;
async function post_vaa(connection: Connection, bridge_id: PublicKey, payer: Keypair, vaa: Buffer) {
let bridge_state = await get_bridge_state(connection, bridge_id);
let guardian_addr = new PublicKey(bridge.guardian_set_address(bridge_id.toString(), bridge_state.guardian_set_index));
let acc = await connection.getAccountInfo(guardian_addr);
if (acc?.data === undefined) {
return
}
let guardian_data = bridge.parse_guardian_set(new Uint8Array(acc?.data));
let signature_set = Keypair.generate();
let txs = bridge.verify_signatures_ix(bridge_id.toString(), payer.publicKey.toString(), bridge_state.guardian_set_index, guardian_data, signature_set.publicKey.toString(), vaa)
// Add transfer instruction to transaction
for (let tx of txs) {
let ixs: Array<TransactionInstruction> = tx.map((v: any) => {
return ixFromRust(v)
})
let transaction = new web3s.Transaction().add(ixs[0], ixs[1]);
// Sign transaction, broadcast, and confirm
await web3s.sendAndConfirmTransaction(
connection,
transaction,
[payer, signature_set],
{
skipPreflight: true
}
);
}
let ix = ixFromRust(bridge.post_vaa_ix(bridge_id.toString(), payer.publicKey.toString(), signature_set.publicKey.toString(), vaa));
let transaction = new web3s.Transaction().add(ix);
// Sign transaction, broadcast, and confirm
let signature = await web3s.sendAndConfirmTransaction(
connection,
transaction,
[payer],
{
skipPreflight: true
}
);
console.log('SIGNATURE', signature);
}
async function get_bridge_state(connection: Connection, bridge_id: PublicKey): Promise<BridgeState> {
let bridge_state = new PublicKey(bridge.state_address(bridge_id.toString()));
let acc = await connection.getAccountInfo(bridge_state);
if (acc?.data === undefined) {
throw new Error("bridge state not found")
}
return bridge.parse_state(new Uint8Array(acc?.data));
}
function setupConnection(argv: yargs.Arguments): web3s.Connection {
return new web3s.Connection(
argv.rpc as string,
'confirmed',
);
}
function ixFromRust(data: any): TransactionInstruction {
let keys: Array<AccountMeta> = data.accounts.map(accountMetaFromRust)
return new TransactionInstruction({
programId: new PublicKey(data.program_id),
data: Buffer.from(data.data),
keys: keys,
})
}
function accountMetaFromRust(meta: any): AccountMeta {
return {
pubkey: new PublicKey(meta.pubkey),
isSigner: meta.is_signer,
isWritable: meta.is_writable,
}
}
interface BridgeState {
// The current guardian set index, used to decide which signature sets to accept.
guardian_set_index: number,
// Lamports in the collection account
last_lamports: number,
// Bridge configuration, which is set once upon initialization.
config: BridgeConfig,
}
interface BridgeConfig {
// Period for how long a guardian set is valid after it has been replaced by a new one. This
// guarantees that VAAs issued by that set can still be submitted for a certain period. In
// this period we still trust the old guardian set.
guardian_set_expiration_time: number,
// Amount of lamports that needs to be paid to the protocol to post a message
fee: number,
}

45927
clients/token_bridge/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
{
"name": "wormhole-client-solana",
"version": "1.0.0",
"dependencies": {
"@solana/web3.js": "^1.22.0",
"bn.js": "^5.2.0",
"bs58": "^4.0.1",
"buffer-layout": "^1.2.2",
"npm": "^7.20.0",
"yargs": "^17.0.1",
"@typechain/ethers-v5": "^7.0.1",
"ethers": "^5.4.1",
"web3": "^1.5.0"
},
"scripts": {
"start": "tsc && node main.js",
"test": "echo \"Error: no test specified\" && exit 1",
"build-contracts": "npm run build --prefix ../../ethereum && node scripts/copyContracts.js && typechain --target=ethers-v5 --out-dir=src/ethers-contracts contracts/*.json"
},
"devDependencies": {
"@types/bn.js": "^5.1.0",
"@types/bs58": "^4.0.1",
"@types/yargs": "^17.0.2",
"bridge": "file:./pkg/core",
"token-bridge": "file:./pkg/token",
"typescript": "^4.3.5",
"@openzeppelin/contracts": "^4.2.0",
"@truffle/hdwallet-provider": "^1.4.1",
"copy-dir": "^1.3.0",
"truffle": "^5.4.1"
}
}

View File

@ -0,0 +1,2 @@
const copydir = require("copy-dir");
copydir.sync("../../ethereum/build/contracts", "./contracts");

View File

@ -0,0 +1,72 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

View File

@ -1,11 +1,11 @@
# Migrations
INIT_SIGNERS=["0xbeFA429d57cD18b7F8A4d91A2da9AB4AF05d0FBe"]
INIT_CHAIN_ID=0x2
INIT_GOV_CHAIN_ID=0x3
INIT_GOV_CHAIN_ID=0x1
INIT_GOV_CONTRACT=0x0000000000000000000000000000000000000000000000000000000000000004
# Bridge Migrations
BRIDGE_INIT_CHAIN_ID=0x02
BRIDGE_INIT_GOV_CHAIN_ID=0x3
BRIDGE_INIT_GOV_CHAIN_ID=0x1
BRIDGE_INIT_GOV_CONTRACT=0x0000000000000000000000000000000000000000000000000000000000000004
BRIDGE_INIT_WETH=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

View File

@ -20,7 +20,7 @@ contract("Bridge", function () {
const testSigner1 = web3.eth.accounts.privateKeyToAccount(testSigner1PK);
const testSigner2 = web3.eth.accounts.privateKeyToAccount(testSigner2PK);
const testChainId = "2";
const testGovernanceChainId = "3";
const testGovernanceChainId = "1";
const testGovernanceContract = "0x0000000000000000000000000000000000000000000000000000000000000004";
let WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const testForeignChainId = "1";

View File

@ -58,7 +58,7 @@ contract("Wormhole", function () {
const testSigner2 = web3.eth.accounts.privateKeyToAccount(testSigner2PK);
const testSigner3 = web3.eth.accounts.privateKeyToAccount(testSigner3PK);
const testChainId = "2";
const testGovernanceChainId = "3";
const testGovernanceChainId = "1";
const testGovernanceContract = "0x0000000000000000000000000000000000000000000000000000000000000004";
it("should be initialized with the correct signers and values", async function () {

View File

@ -17,4 +17,5 @@ set -euo pipefail
-e EMITTER_ADDRESS=11111111111111111111111111111115 \
localhost/certusone/wormhole-wasmpack:latest \
/usr/local/cargo/bin/wasm-pack build --target nodejs -- --features wasm
cp $(pwd)/../bridge_ui/rust_modules/. $(pwd)/../clients/token_bridge/pkg -R
)

View File

@ -309,11 +309,13 @@ pub fn create_wrapped_ix(
#[wasm_bindgen]
pub fn upgrade_contract_ix(
program_id: String,
bridge_id: String,
payer: String,
spill: String,
vaa: Vec<u8>,
) -> JsValue {
let program_id = Pubkey::from_str(program_id.as_str()).unwrap();
let bridge_id = Pubkey::from_str(bridge_id.as_str()).unwrap();
let spill = Pubkey::from_str(spill.as_str()).unwrap();
let vaa = VAA::deserialize(vaa.as_slice()).unwrap();
let payload = GovernancePayloadUpgrade::deserialize(&mut vaa.payload.as_slice()).unwrap();
@ -325,7 +327,7 @@ pub fn upgrade_contract_ix(
payload: vaa.payload,
sequence: None,
},
&program_id,
&bridge_id,
);
let ix = upgrade_contract(
program_id,
@ -359,7 +361,7 @@ pub fn register_chain_ix(
payload: vaa.payload.clone(),
sequence: None,
},
&program_id,
&bridge_id,
);
let post_vaa_data = PostVAAData {
version: vaa.version,