From 6074498f3a5503de3b5584506747074a3d3084d9 Mon Sep 17 00:00:00 2001 From: Alex Freska Date: Thu, 29 Feb 2024 15:05:44 -0500 Subject: [PATCH] refactor: migrate wallet wasm into sdk --- .changeset/real-carrots-cry.md | 5 + go.work | 4 +- go.work.sum | 10 ++ libs/sdk/src/rhp.spec.ts | 283 ++++++++++++++++++++++++++++++++ libs/sdk/src/sdk.ts | 3 +- libs/sdk/src/types.ts | 56 ++++++- libs/sdk/src/wasm.spec.ts | 290 --------------------------------- sdk/go.mod | 6 +- sdk/go.sum | 8 + sdk/main.go | 10 ++ sdk/wallet/core.go | 62 +++++++ sdk/wallet/wallet.go | 189 +++++++++++++++++++++ 12 files changed, 628 insertions(+), 298 deletions(-) create mode 100644 .changeset/real-carrots-cry.md create mode 100644 libs/sdk/src/rhp.spec.ts delete mode 100644 libs/sdk/src/wasm.spec.ts create mode 100644 sdk/wallet/core.go create mode 100644 sdk/wallet/wallet.go diff --git a/.changeset/real-carrots-cry.md b/.changeset/real-carrots-cry.md new file mode 100644 index 000000000..f45f5ce27 --- /dev/null +++ b/.changeset/real-carrots-cry.md @@ -0,0 +1,5 @@ +--- +'@siafoundation/sdk': minor +--- + +Wallet and transaction signing methods are now part of the sdk. diff --git a/go.work b/go.work index 390c0833d..b2201135d 100644 --- a/go.work +++ b/go.work @@ -1,9 +1,9 @@ -go 1.20 +go 1.21.7 use ( ./ ./hostd ./renterd - ./walletd ./sdk + ./walletd ) diff --git a/go.work.sum b/go.work.sum index 87555cbed..9c5b6b513 100644 --- a/go.work.sum +++ b/go.work.sum @@ -1 +1,11 @@ +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M= go.sia.tech/mux v1.2.0/go.mod h1:Yyo6wZelOYTyvrHmJZ6aQfRoer3o4xyKQ4NmQLJrBSo= +go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/libs/sdk/src/rhp.spec.ts b/libs/sdk/src/rhp.spec.ts new file mode 100644 index 000000000..300c42769 --- /dev/null +++ b/libs/sdk/src/rhp.spec.ts @@ -0,0 +1,283 @@ +import { + HostPrices, + HostSettings, + RPCReadSectorRequest, + RPCReadSectorResponse, + RPCSettingsResponse, + RPCWriteSectorRequest, + RPCWriteSectorResponse, +} from './types' +import { initSDKTest } from './initTest' + +describe('rhp', () => { + describe('generateAccout', () => { + it('works', async () => { + const sdk = await initSDKTest() + const { privateKey, account, error } = sdk.rhp.generateAccount() + expect(error).toBeUndefined() + expect(privateKey).toBeDefined() + expect(privateKey?.length).toBeGreaterThan(40) + expect(account).toBeDefined() + expect(account?.length).toBeGreaterThan(40) + }) + }) + describe('settings', () => { + describe('request', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const encode = sdk.rhp.encodeSettingsRequest() + expect(encode.rpc).toBeDefined() + expect(encode.error).not.toBeDefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeSettingsRequest(encode.rpc) + expect(decode.data).toEqual({}) + expect(decode.error).toBeUndefined() + }) + }) + describe('response', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const json = getSampleRPCSettingsResponse() + const encode = sdk.rhp.encodeSettingsResponse(json) + expect(encode.rpc).toBeDefined() + expect(encode.rpc?.length).toEqual(323) + expect(encode.error).toBeUndefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeSettingsResponse(encode.rpc) + expect(decode.data).toEqual(json) + expect(decode.error).toBeUndefined() + }) + it('encode error', async () => { + const sdk = await initSDKTest() + const json = { + settings: { + walletAddress: 'invalid', + }, + } as RPCSettingsResponse + const encode = sdk.rhp.encodeSettingsResponse(json) + expect(encode.rpc).toBeUndefined() + expect(encode.error).toEqual( + "decoding addr: failed: encoding/hex: invalid byte: U+0069 'i'" + ) + }) + it('decode error', async () => { + const sdk = await initSDKTest() + const json = getSampleRPCSettingsResponse() + const encode = sdk.rhp.encodeSettingsResponse(json) + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + // manipulate the valid rpc to make it invalid + encode.rpc.set([1, 1], 30) + const decode = sdk.rhp.decodeSettingsResponse(encode.rpc) + expect(decode.data).not.toEqual(json) + expect(decode.error).toEqual( + 'encoded object contains invalid length prefix (65806 elems > 11227 bytes left in stream)' + ) + }) + }) + }) + describe('read', () => { + describe('request', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const json: RPCReadSectorRequest = { + token: { + account: + 'acct:1b6793e900df020dc9a43c6df5f5d10dc5793956d44831ca5bbfec659021b75e', + validUntil: '2022-12-31T00:00:00Z', + signature: + 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', + }, + root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', + prices: getSampleHostPrices(), + offset: 0, + length: 4, + } + const encode = sdk.rhp.encodeReadSectorRequest(json) + expect(encode.rpc?.length).toEqual(312) + expect(encode.error).toBeUndefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeReadSectorRequest(encode.rpc) + expect(decode.data).toEqual(json) + expect(decode.error).toBeUndefined() + }) + it('encode error', async () => { + const sdk = await initSDKTest() + const json: RPCReadSectorRequest = { + token: { + account: 'invalid', + validUntil: '2022-12-31T00:00:00Z', + signature: + 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', + }, + root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', + prices: getSampleHostPrices(), + offset: 0, + length: 4, + } + const encode = sdk.rhp.encodeReadSectorRequest(json) + expect(encode.rpc).toBeUndefined() + expect(encode.error).toEqual( + "decoding acct: failed: encoding/hex: invalid byte: U+0069 'i'" + ) + }) + }) + describe('response', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const json: RPCReadSectorResponse = { + proof: [ + 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', + ], + sector: 'AQID', + } + const encode = sdk.rhp.encodeReadSectorResponse(json) + expect(encode.rpc?.toString()).toEqual( + [ + 0, 1, 0, 0, 0, 0, 0, 0, 0, 69, 114, 86, 214, 161, 96, 59, 239, 127, + 169, 87, 167, 11, 91, 169, 106, 157, 239, 47, 234, 139, 76, 20, 131, + 6, 13, 123, 165, 207, 138, 7, 44, 3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, + ].toString() + ) + expect(encode.error).toBeUndefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeReadSectorResponse(encode.rpc) + expect(decode.data).toEqual(json) + expect(decode.error).toBeUndefined() + }) + it('encode error', async () => { + const sdk = await initSDKTest() + const json: RPCReadSectorResponse = { + proof: ['invalid'], + sector: 'AQID', + } + const encode = sdk.rhp.encodeReadSectorResponse(json) + expect(encode.rpc).toBeUndefined() + expect(encode.error).toEqual('decoding h: failed: unexpected EOF') + }) + }) + }) + describe('write', () => { + describe('request', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const json: RPCWriteSectorRequest = { + token: { + account: + 'acct:1b6793e900df020dc9a43c6df5f5d10dc5793956d44831ca5bbfec659021b75e', + validUntil: '2022-12-31T00:00:00Z', + signature: + 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', + }, + sector: 'AQID', + prices: getSampleHostPrices(), + } + const encode = sdk.rhp.encodeWriteSectorRequest(json) + expect(encode.rpc?.length).toEqual(275) + expect(encode.error).toBeUndefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeWriteSectorRequest(encode.rpc) + expect(decode.data).toEqual(json) + expect(decode.error).toBeUndefined() + }) + it('encode error', async () => { + const sdk = await initSDKTest() + const json = { + token: { + account: 'invalid', + validUntil: '2022-12-31T00:00:00Z', + signature: + 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', + }, + sector: 'AQID', + prices: getSampleHostPrices(), + } as RPCWriteSectorRequest + const encode = sdk.rhp.encodeWriteSectorRequest(json) + expect(encode.rpc).toBeUndefined() + expect(encode.error).toEqual( + "decoding acct: failed: encoding/hex: invalid byte: U+0069 'i'" + ) + }) + }) + describe('response', () => { + it('valid', async () => { + const sdk = await initSDKTest() + const json: RPCWriteSectorResponse = { + root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', + } + const encode = sdk.rhp.encodeWriteSectorResponse(json) + expect(encode.rpc?.toString()).toEqual( + [ + 0, 69, 114, 86, 214, 161, 96, 59, 239, 127, 169, 87, 167, 11, 91, + 169, 106, 157, 239, 47, 234, 139, 76, 20, 131, 6, 13, 123, 165, 207, + 138, 7, 44, + ].toString() + ) + expect(encode.error).toBeUndefined() + if (!encode.rpc) { + throw new Error('rpc is undefined') + } + const decode = sdk.rhp.decodeWriteSectorResponse(encode.rpc) + expect(decode.data).toEqual(json) + expect(decode.error).toBeUndefined() + }) + it('encode error', async () => { + const sdk = await initSDKTest() + const json = { + root: 'invalid', + } as RPCWriteSectorResponse + const encode = sdk.rhp.encodeWriteSectorResponse(json) + expect(encode.rpc).toBeUndefined() + expect(encode.error).toEqual('decoding h: failed: unexpected EOF') + }) + }) + }) +}) + +function getSampleHostPrices(): HostPrices { + return { + contractPrice: '1000000000', + collateral: '2000000000', + storagePrice: '3000000000', + ingressPrice: '4000000000', + egressPrice: '5000000000', + tipHeight: 450_000, + validUntil: '2022-12-31T00:00:00Z', + signature: + 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', + } +} + +function getSampleRPCSettingsResponse(): RPCSettingsResponse { + const prices = getSampleHostPrices() + const settings: HostSettings = { + version: [1, 2, 3], + netAddresses: [ + { protocol: 'protocol1', address: 'address1longer' }, + { protocol: 'protocol2longer', address: 'address2' }, + ], + // 32 bytes + walletAddress: + 'addr:eec8160897cf7058332040675d120c008dc32d96925e9b32a812b646e31676d7d52c118cad2c', + acceptingContracts: true, + maxCollateral: '1000000000', + maxDuration: 100, + remainingStorage: 100, + totalStorage: 100, + prices, + } + return { + settings, + } +} diff --git a/libs/sdk/src/sdk.ts b/libs/sdk/src/sdk.ts index 0cd01daac..948d8a4c6 100644 --- a/libs/sdk/src/sdk.ts +++ b/libs/sdk/src/sdk.ts @@ -5,7 +5,8 @@ export function getSDK() { // eslint-disable-next-line @typescript-eslint/no-explicit-any const wasm = (global as any).sia as WASM return { - wasm, + rhp: wasm.rhp, + wallet: wasm.wallet, WebTransportClient, } } diff --git a/libs/sdk/src/types.ts b/libs/sdk/src/types.ts index 87e64ef04..47a8ad82e 100644 --- a/libs/sdk/src/types.ts +++ b/libs/sdk/src/types.ts @@ -1,3 +1,5 @@ +import { Transaction, UnlockConditions } from '@siafoundation/types' + type Currency = string type Signature = string type Address = string @@ -88,10 +90,8 @@ export type RPC = RPCSettings | RPCReadSector | RPCWriteSector export type WASM = { rhp: { generateAccount: () => { - data?: { - privateKey: PrivateKey - account?: PublicKey - } + privateKey?: PrivateKey + account?: PublicKey error?: string } // settings @@ -146,4 +146,52 @@ export type WASM = { error?: string } } + wallet: { + newSeedPhrase: () => { + phrase?: string + error?: string + } + seedFromPhrase: (phrase: string) => { + seed?: string + error?: string + } + privateKeyFromSeed: ( + seed: string, + index: number + ) => { + privateKey?: string + error?: string + } + unlockConditionsFromSeed: ( + seed: string, + index: number + ) => { + unlockConditions?: UnlockConditions + error?: string + } + publicKeyAndAddressFromSeed: ( + seed: string, + index: number + ) => { + publicKey?: string + address?: string + error?: string + } + encodeTransaction: ( + txn: string // Transaction + ) => { + encodedTransaction?: string + error?: string + } + signTransaction: ( + cs: string, // ConsensusState + cn: string, // ConsensusNetwork + txn: string, // Transaction + sigIndex: number, + seed: string + ) => { + transaction?: Transaction + error?: string + } + } } diff --git a/libs/sdk/src/wasm.spec.ts b/libs/sdk/src/wasm.spec.ts deleted file mode 100644 index 7c99ac155..000000000 --- a/libs/sdk/src/wasm.spec.ts +++ /dev/null @@ -1,290 +0,0 @@ -import { - HostPrices, - HostSettings, - RPCReadSectorRequest, - RPCReadSectorResponse, - RPCSettingsResponse, - RPCWriteSectorRequest, - RPCWriteSectorResponse, -} from './types' -import { initSDKTest } from './initTest' - -describe('wasm', () => { - describe('rhp', () => { - describe('generateAccout', () => { - it('works', async () => { - const sdk = await initSDKTest() - const { data, error } = sdk.wasm.rhp.generateAccount() - expect(error).toBeUndefined() - expect(data?.privateKey).toBeDefined() - expect(data?.privateKey?.length).toBeGreaterThan(40) - expect(data?.account).toBeDefined() - expect(data?.account?.length).toBeGreaterThan(40) - }) - }) - describe('settings', () => { - describe('request', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const encode = sdk.wasm.rhp.encodeSettingsRequest() - expect(encode.rpc).toBeDefined() - expect(encode.error).not.toBeDefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeSettingsRequest(encode.rpc) - expect(decode.data).toEqual({}) - expect(decode.error).toBeUndefined() - }) - }) - describe('response', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const json = getSampleRPCSettingsResponse() - const encode = sdk.wasm.rhp.encodeSettingsResponse(json) - expect(encode.rpc).toBeDefined() - expect(encode.rpc?.length).toEqual(323) - expect(encode.error).toBeUndefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeSettingsResponse(encode.rpc) - expect(decode.data).toEqual(json) - expect(decode.error).toBeUndefined() - }) - it('encode error', async () => { - const sdk = await initSDKTest() - const json = { - settings: { - walletAddress: 'invalid', - }, - } as RPCSettingsResponse - const encode = sdk.wasm.rhp.encodeSettingsResponse(json) - expect(encode.rpc).toBeUndefined() - expect(encode.error).toEqual( - "decoding addr: failed: encoding/hex: invalid byte: U+0069 'i'" - ) - }) - it('decode error', async () => { - const sdk = await initSDKTest() - const json = getSampleRPCSettingsResponse() - const encode = sdk.wasm.rhp.encodeSettingsResponse(json) - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - // manipulate the valid rpc to make it invalid - encode.rpc.set([1, 1], 30) - const decode = sdk.wasm.rhp.decodeSettingsResponse(encode.rpc) - expect(decode.data).not.toEqual(json) - expect(decode.error).toEqual( - 'encoded object contains invalid length prefix (65806 elems > 11227 bytes left in stream)' - ) - }) - }) - }) - describe('read', () => { - describe('request', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const json: RPCReadSectorRequest = { - token: { - account: - 'acct:1b6793e900df020dc9a43c6df5f5d10dc5793956d44831ca5bbfec659021b75e', - validUntil: '2022-12-31T00:00:00Z', - signature: - 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', - }, - root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', - prices: getSampleHostPrices(), - offset: 0, - length: 4, - } - const encode = sdk.wasm.rhp.encodeReadSectorRequest(json) - expect(encode.rpc?.length).toEqual(312) - expect(encode.error).toBeUndefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeReadSectorRequest(encode.rpc) - expect(decode.data).toEqual(json) - expect(decode.error).toBeUndefined() - }) - it('encode error', async () => { - const sdk = await initSDKTest() - const json: RPCReadSectorRequest = { - token: { - account: 'invalid', - validUntil: '2022-12-31T00:00:00Z', - signature: - 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', - }, - root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', - prices: getSampleHostPrices(), - offset: 0, - length: 4, - } - const encode = sdk.wasm.rhp.encodeReadSectorRequest(json) - expect(encode.rpc).toBeUndefined() - expect(encode.error).toEqual( - "decoding acct: failed: encoding/hex: invalid byte: U+0069 'i'" - ) - }) - }) - describe('response', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const json: RPCReadSectorResponse = { - proof: [ - 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', - ], - sector: 'AQID', - } - const encode = sdk.wasm.rhp.encodeReadSectorResponse(json) - expect(encode.rpc?.toString()).toEqual( - [ - 0, 1, 0, 0, 0, 0, 0, 0, 0, 69, 114, 86, 214, 161, 96, 59, 239, - 127, 169, 87, 167, 11, 91, 169, 106, 157, 239, 47, 234, 139, 76, - 20, 131, 6, 13, 123, 165, 207, 138, 7, 44, 3, 0, 0, 0, 0, 0, 0, 0, - 1, 2, 3, - ].toString() - ) - expect(encode.error).toBeUndefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeReadSectorResponse(encode.rpc) - expect(decode.data).toEqual(json) - expect(decode.error).toBeUndefined() - }) - it('encode error', async () => { - const sdk = await initSDKTest() - const json: RPCReadSectorResponse = { - proof: ['invalid'], - sector: 'AQID', - } - const encode = sdk.wasm.rhp.encodeReadSectorResponse(json) - expect(encode.rpc).toBeUndefined() - expect(encode.error).toEqual( - 'decoding h: failed: unexpected EOF' - ) - }) - }) - }) - describe('write', () => { - describe('request', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const json: RPCWriteSectorRequest = { - token: { - account: - 'acct:1b6793e900df020dc9a43c6df5f5d10dc5793956d44831ca5bbfec659021b75e', - validUntil: '2022-12-31T00:00:00Z', - signature: - 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', - }, - sector: 'AQID', - prices: getSampleHostPrices(), - } - const encode = sdk.wasm.rhp.encodeWriteSectorRequest(json) - expect(encode.rpc?.length).toEqual(275) - expect(encode.error).toBeUndefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeWriteSectorRequest(encode.rpc) - expect(decode.data).toEqual(json) - expect(decode.error).toBeUndefined() - }) - it('encode error', async () => { - const sdk = await initSDKTest() - const json = { - token: { - account: 'invalid', - validUntil: '2022-12-31T00:00:00Z', - signature: - 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', - }, - sector: 'AQID', - prices: getSampleHostPrices(), - } as RPCWriteSectorRequest - const encode = sdk.wasm.rhp.encodeWriteSectorRequest(json) - expect(encode.rpc).toBeUndefined() - expect(encode.error).toEqual( - "decoding acct: failed: encoding/hex: invalid byte: U+0069 'i'" - ) - }) - }) - describe('response', () => { - it('valid', async () => { - const sdk = await initSDKTest() - const json: RPCWriteSectorResponse = { - root: 'h:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072c', - } - const encode = sdk.wasm.rhp.encodeWriteSectorResponse(json) - expect(encode.rpc?.toString()).toEqual( - [ - 0, 69, 114, 86, 214, 161, 96, 59, 239, 127, 169, 87, 167, 11, 91, - 169, 106, 157, 239, 47, 234, 139, 76, 20, 131, 6, 13, 123, 165, - 207, 138, 7, 44, - ].toString() - ) - expect(encode.error).toBeUndefined() - if (!encode.rpc) { - throw new Error('rpc is undefined') - } - const decode = sdk.wasm.rhp.decodeWriteSectorResponse(encode.rpc) - expect(decode.data).toEqual(json) - expect(decode.error).toBeUndefined() - }) - it('encode error', async () => { - const sdk = await initSDKTest() - const json = { - root: 'invalid', - } as RPCWriteSectorResponse - const encode = sdk.wasm.rhp.encodeWriteSectorResponse(json) - expect(encode.rpc).toBeUndefined() - expect(encode.error).toEqual( - 'decoding h: failed: unexpected EOF' - ) - }) - }) - }) - }) -}) - -function getSampleHostPrices(): HostPrices { - return { - contractPrice: '1000000000', - collateral: '2000000000', - storagePrice: '3000000000', - ingressPrice: '4000000000', - egressPrice: '5000000000', - tipHeight: 450_000, - validUntil: '2022-12-31T00:00:00Z', - signature: - 'sig:457256d6a1603bef7fa957a70b5ba96a9def2fea8b4c1483060d7ba5cf8a072cfddf242a1ef033dd7d669c711e846c59cb916f804a03d72d279ffef7e6583404', - } -} - -function getSampleRPCSettingsResponse(): RPCSettingsResponse { - const prices = getSampleHostPrices() - const settings: HostSettings = { - version: [1, 2, 3], - netAddresses: [ - { protocol: 'protocol1', address: 'address1longer' }, - { protocol: 'protocol2longer', address: 'address2' }, - ], - // 32 bytes - walletAddress: - 'addr:eec8160897cf7058332040675d120c008dc32d96925e9b32a812b646e31676d7d52c118cad2c', - acceptingContracts: true, - maxCollateral: '1000000000', - maxDuration: 100, - remainingStorage: 100, - totalStorage: 100, - prices, - } - return { - settings, - } -} diff --git a/sdk/go.mod b/sdk/go.mod index dee208d71..da4795d5e 100644 --- a/sdk/go.mod +++ b/sdk/go.mod @@ -1,6 +1,6 @@ module go.sia.tech/web/sdk -go 1.20 +go 1.21.7 require ( go.sia.tech/core v0.2.2-0.20240229154321-d97c1d5b2172 @@ -9,6 +9,10 @@ require ( require ( github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da // indirect + go.etcd.io/bbolt v1.3.8 // indirect + go.sia.tech/coreutils v0.0.3 // indirect + go.uber.org/multierr v1.10.0 // indirect + go.uber.org/zap v1.26.0 // indirect golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 // indirect golang.org/x/sys v0.5.0 // indirect lukechampine.com/frand v1.4.2 // indirect diff --git a/sdk/go.sum b/sdk/go.sum index 7470405a9..663d85f74 100644 --- a/sdk/go.sum +++ b/sdk/go.sum @@ -1,5 +1,7 @@ github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY= github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA= +go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA= +go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= go.sia.tech/core v0.1.12-0.20230807160906-ad76cac3058f h1:ZPWqj1RphySPSdVvhW09VYI/nKc+TiqJlUnx9FcI0lY= go.sia.tech/core v0.1.12-0.20230807160906-ad76cac3058f/go.mod h1:D17UWSn99SEfQnEaR9G9n6Kz9+BwqMoUgZ6Cl424LsQ= go.sia.tech/core v0.2.2-0.20240202170315-3e6d0eca7490 h1:pfmR0dva8GQ1Oxb5VpF7JWfDuWgmfbgZKK8oAKWT24g= @@ -10,8 +12,14 @@ go.sia.tech/core v0.2.2-0.20240229150213-044552edecf7 h1:YDurKmoU+oVzlZgAcaDSTrd go.sia.tech/core v0.2.2-0.20240229150213-044552edecf7/go.mod h1:3EoY+rR78w1/uGoXXVqcYdwSjSJKuEMI5bL7WROA27Q= go.sia.tech/core v0.2.2-0.20240229154321-d97c1d5b2172 h1:uET7VyK5mz02bsicyNeoEut/RarvmQXAvXgUqZ1YJoE= go.sia.tech/core v0.2.2-0.20240229154321-d97c1d5b2172/go.mod h1:3EoY+rR78w1/uGoXXVqcYdwSjSJKuEMI5bL7WROA27Q= +go.sia.tech/coreutils v0.0.3 h1:ZxuzovRpQMvfy/pCOV4om1cPF6sE15GyJyK36kIrF1Y= +go.sia.tech/coreutils v0.0.3/go.mod h1:UBFc77wXiE//eyilO5HLOncIEj7F69j0Nv2OkFujtP0= go.sia.tech/web v0.0.0-20230628194305-c6e1696bad89 h1:wB/JRFeTEs6gviB6k7QARY7Goh54ufkADsdBdn0ZhRo= go.sia.tech/web v0.0.0-20230628194305-c6e1696bad89/go.mod h1:RKODSdOmR3VtObPAcGwQqm4qnqntDVFylbvOBbWYYBU= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= +go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 h1:NvGWuYG8dkDHFSKksI1P9faiVJ9rayE6l0+ouWVIDs8= golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/sdk/main.go b/sdk/main.go index 93fd0a5c4..570466ee9 100644 --- a/sdk/main.go +++ b/sdk/main.go @@ -4,6 +4,7 @@ import ( "syscall/js" "go.sia.tech/web/sdk/rhp" + "go.sia.tech/web/sdk/wallet" ) func main() { @@ -26,6 +27,15 @@ func main() { "encodeWriteSectorResponse": js.FuncOf(rhp.EncodeWriteSectorResponse), "decodeWriteSectorResponse": js.FuncOf(rhp.DecodeWriteSectorResponse), }, + "wallet": map[string]interface{}{ + "newSeedPhrase": js.FuncOf(wallet.NewSeedPhrase), + "seedFromPhrase": js.FuncOf(wallet.SeedFromPhrase), + "privateKeyFromSeed": js.FuncOf(wallet.PrivateKeyFromSeed), + "unlockConditionsFromSeed": js.FuncOf(wallet.UnlockConditionsFromSeed), + "publicKeyAndAddressFromSeed": js.FuncOf(wallet.PublicKeyAndAddressFromSeed), + "encodeTransaction": js.FuncOf(wallet.EncodeTransaction), + "signTransaction": js.FuncOf(wallet.SignTransaction), + }, }) c := make(chan bool, 1) <-c diff --git a/sdk/wallet/core.go b/sdk/wallet/core.go new file mode 100644 index 000000000..9dfb3155c --- /dev/null +++ b/sdk/wallet/core.go @@ -0,0 +1,62 @@ +package wallet + +import ( + "bytes" + + "go.sia.tech/core/consensus" + "go.sia.tech/core/types" + "go.sia.tech/coreutils/wallet" +) + +func newSeedPhrase() string { + return wallet.NewSeedPhrase() +} + +func seedFromPhrase(phrase string) (*[32]byte, error) { + var seed [32]byte + return &seed, wallet.SeedFromPhrase(&seed, phrase) +} + +func privateKeyFromSeed(seed *[32]byte, index uint64) types.PrivateKey { + return wallet.KeyFromSeed(seed, index) +} + +func publicKeyFromSeed(seed *[32]byte, index uint64) string { + return wallet.KeyFromSeed(seed, index).PublicKey().String() +} + +func publicKeyAndAddressFromSeed(seed *[32]byte, index uint64) (string, string) { + pk := wallet.KeyFromSeed(seed, index).PublicKey() + publicKey := pk.String() + address := types.StandardUnlockConditions(pk).UnlockHash().String() + return publicKey, address +} + +func encodeToBytes(v types.EncoderTo) []byte { + var buf bytes.Buffer + e := types.NewEncoder(&buf) + v.EncodeTo(e) + e.Flush() + return buf.Bytes() +} + +func encodeTransaction(txn types.Transaction) []byte { + return encodeToBytes(txn) +} + +func signTransaction(cs consensus.State, txn types.Transaction, sigIndex int, key types.PrivateKey) types.Transaction { + tsig := &txn.Signatures[sigIndex] + var sigHash types.Hash256 + if tsig.CoveredFields.WholeTransaction { + sigHash = cs.WholeSigHash(txn, tsig.ParentID, tsig.PublicKeyIndex, tsig.Timelock, tsig.CoveredFields.Signatures) + } else { + sigHash = cs.PartialSigHash(txn, tsig.CoveredFields) + } + sig := key.SignHash(sigHash) + tsig.Signature = sig[:] + return txn +} + +func unlockConditionsFromSeed(seed *[32]byte, index uint64) types.UnlockConditions { + return types.StandardUnlockConditions(wallet.KeyFromSeed(seed, index).PublicKey()) +} diff --git a/sdk/wallet/wallet.go b/sdk/wallet/wallet.go new file mode 100644 index 000000000..9e359dab1 --- /dev/null +++ b/sdk/wallet/wallet.go @@ -0,0 +1,189 @@ +package wallet + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "log" + "strings" + "syscall/js" + + "go.sia.tech/core/consensus" + "go.sia.tech/core/types" + "go.sia.tech/web/sdk/marshal" + "go.sia.tech/web/sdk/utils" +) + +func NewSeedPhrase(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args); err != nil { + return map[string]any{"error": err.Error()} + } + + return map[string]any{ + "phrase": newSeedPhrase(), + } +} + +func SeedFromPhrase(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString); err != nil { + return map[string]any{"error": err.Error()} + } + + phrase := args[0].String() + seed, err := seedFromPhrase(phrase) + + if err != nil { + return map[string]any{"error": err.Error()} + } + + seedHex := hex.EncodeToString(seed[:]) + return map[string]any{ + "seed": seedHex, + } +} + +func PrivateKeyFromSeed(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString, js.TypeNumber); err != nil { + return map[string]any{"error": err.Error()} + } + + seed := hexStringToByte32Array(args[0].String()) + index := uint64(args[1].Int()) + privateKey := privateKeyFromSeed(&seed, index) + return map[string]any{ + "privateKey": hex.EncodeToString(privateKey), + } +} + +func UnlockConditionsFromSeed(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString, js.TypeNumber); err != nil { + return map[string]any{"error": err.Error()} + } + + seed := hexStringToByte32Array(args[0].String()) + index := uint64(args[1].Int()) + unlockConditions := unlockConditionsFromSeed(&seed, index) + + data, err := marshal.MarshalStruct(unlockConditions) + if err != nil { + return map[string]any{"error": err} + } + return map[string]any{ + "unlockConditions": data, + } +} + +func PublicKeyAndAddressFromSeed(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString, js.TypeNumber); err != nil { + return map[string]any{"error": err.Error()} + } + + seed := hexStringToByte32Array(args[0].String()) + index := uint64(args[1].Int()) + publicKey, address := publicKeyAndAddressFromSeed(&seed, index) + return map[string]any{ + "publicKey": publicKey, + "address": address, + } +} + +func EncodeTransaction(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString); err != nil { + return map[string]any{"error": err.Error()} + } + + jsonTxn := args[0].String() + + var txn types.Transaction + + if err := json.Unmarshal([]byte(jsonTxn), &txn); err != nil { + return map[string]any{"error": err.Error()} + } + + encoded := encodeTransaction(txn) + + return map[string]any{ + "encodedTransaction": bytesToInterface(encoded), + } +} + +func SignTransaction(this js.Value, args []js.Value) interface{} { + if err := utils.CheckArgs(args, js.TypeString, js.TypeString, js.TypeString, js.TypeNumber, js.TypeString); err != nil { + return map[string]any{"error": err.Error()} + } + + jsonCs := args[0].String() + jsonCn := args[1].String() + jsonTxn := args[2].String() + sigIndex := args[3].Int() + seed := hexStringToByteArray(args[4].String()) + + var cs consensus.State + if err := json.Unmarshal([]byte(jsonCs), &cs); err != nil { + return map[string]any{ + "error": fmt.Sprintf("error decoding consensus state: %s", err), + } + } + + var cn consensus.Network + if err := json.Unmarshal([]byte(jsonCn), &cn); err != nil { + return map[string]any{ + "error": fmt.Sprintf("error decoding consensus network: %s", err), + } + } + + var txn types.Transaction + if err := json.Unmarshal([]byte(jsonTxn), &txn); err != nil { + return map[string]any{ + "error": fmt.Sprintf("error decoding transaction: %s", err), + } + } + cs.Network = &cn + + signedTxn := signTransaction(cs, txn, sigIndex, seed) + data, err := marshal.MarshalStruct(signedTxn) + if err != nil { + return map[string]any{"error": err} + } + return map[string]any{ + "transaction": data, + } +} + +func hexStringToByteArray(str string) []byte { + byteArray, err := hex.DecodeString(str) + if err != nil { + log.Fatal(err) + } + + return byteArray +} + +func hexStringToByte32Array(str string) [32]byte { + // The length of the hexString should be 64 to fit in [32]byte. + // If the hexString is shorter, pad it with zeroes. + if len(str) < 64 { + fmt.Println("WARNING: not 64 characters") + str = str + strings.Repeat("0", 64-len(str)) + } + + byteArray, err := hex.DecodeString(str) + if err != nil { + log.Fatal(err) + } + + var byte32Array [32]byte + copy(byte32Array[:], byteArray[:32]) + + return byte32Array +} + +func bytesToInterface(bytes []byte) []interface{} { + value := make([]interface{}, len(bytes)) + + for i, b := range bytes { + value[i] = b + } + + return value +}