Skip to content

Commit

Permalink
👌 IMPROVE: Add path support to sign transactions api
Browse files Browse the repository at this point in the history
  • Loading branch information
riverrun46 committed Sep 22, 2023
1 parent 0038f5f commit 8aafb43
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
6 changes: 4 additions & 2 deletions src/lib/actions/sign-transactions.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { getAddress, getCurrentAccount, privateKey } from '../account'
import connector from '../connector'
import { signTransaction, signTransactions } from '../crypto'
import { getNetwork } from '../network'

export async function process(params: any, host: string) {
const wif = await getCurrentAccount().then((account) => privateKey.value)
const account = await getCurrentAccount()
const network = await getNetwork()

const signingTransactions = params.transactions
const signedTransactions = signTransactions(wif, signingTransactions)
const signedTransactions = signTransactions(account!, network, signingTransactions)

return { signedTransactions }
}
18 changes: 15 additions & 3 deletions src/lib/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BN, mvc } from 'meta-contract'
import { Buffer } from 'buffer'
import { type Account } from './account'

export function eciesEncrypt(message: string, privateKey: mvc.PrivateKey): string {
const publicKey = privateKey.toPublicKey()
Expand Down Expand Up @@ -72,6 +73,7 @@ type ToSignTransaction = {
inputIndex: number
satoshis: number
sigtype?: number
path?: string
}
export const signTransaction = (
wif: string,
Expand Down Expand Up @@ -114,9 +116,14 @@ export const signTransaction = (
}
}

export const signTransactions = (wif: string, toSignTransactions: ToSignTransaction[]) => {
const privateKey = mvc.PrivateKey.fromWIF(wif)
const publicKey = privateKey.toPublicKey()
export const signTransactions = (
account: Account,
network: 'testnet' | 'mainnet',
toSignTransactions: ToSignTransaction[]
) => {
const mneObj = mvc.Mnemonic.fromString(account.mnemonic)
const hdpk = mneObj.toHDPrivateKey('', network)
const accountPath = account.path

// find out if transactions other than the first one are dependent on previous ones
// if so, we need to sign them in order, and sequentially update the prevTxId of the later ones
Expand Down Expand Up @@ -160,6 +167,11 @@ export const signTransactions = (wif: string, toSignTransactions: ToSignTransact
tx.inputs[inputIndex].prevTxId = Buffer.from(prevTxId, 'hex')
}

// find out priv / pub according to path
const subPath = toSign.path || '0/0'
const privateKey = hdpk.deriveChild(`m/44'/${accountPath}'/0'/${subPath}`).privateKey
const publicKey = privateKey.toPublicKey()

// Build signature of this input
const signature = mvc.Transaction.Sighash.sign(
tx,
Expand Down

0 comments on commit 8aafb43

Please sign in to comment.