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

[MultiSig] Implement 2 steps (resolveMultisigIndices -> sign) #48

Merged
merged 1 commit into from
Mar 13, 2023
Merged
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
135 changes: 79 additions & 56 deletions examples/platformvm/buildExportTx-XChain-Msig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Avalanche, BN, Buffer } from "caminojs/index"
import { Avalanche, BinTools, BN, Buffer } from "caminojs/index"
import { AVMAPI, KeyChain as AVMKeyChain } from "caminojs/apis/avm"
import {
PlatformVMAPI,
Expand All @@ -8,36 +8,42 @@ import {
Tx
} from "caminojs/apis/platformvm"
import {
MultiSigAliasSet,
MultiSigKeyChain,
MultiSigKeyPair,
MultisigAliasSet,
MultisigKeyChain,
MultisigKeyPair,
OutputOwners
} from "caminojs/common"

import {
PrivateKeyPrefix,
DefaultLocalGenesisPrivateKey,
DefaultLocalGenesisPrivateKey2,
PChainAlias
} from "caminojs/utils"
import { ExamplesConfig } from "../common/examplesConfig"
import createHash from "create-hash"

const config: ExamplesConfig = require("../common/examplesConfig.json")
const bintools = BinTools.getInstance()
const avalanche: Avalanche = new Avalanche(
config.host,
config.port,
config.protocol,
config.networkID
)

const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey2}`
const privKey1: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey2}`
const privKey2: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
"PlatformVM utility method buildExportTx to export AVAX from the P-Chain to the X-Chain using multisig"
)
const asOf: BN = new BN(0)
const msigAlias = "P-kopernikus1fq0jc8svlyazhygkj0s36qnl6s0km0h3uuc99w"
const msigAliasArray = [
"P-kopernikus1fq0jc8svlyazhygkj0s36qnl6s0km0h3uuc99w",
"P-kopernikus1k4przmfu79ypp4u7y98glmdpzwk0u3sc7saazy"
]

let pchain: PlatformVMAPI
let pKeychain: KeyChain
Expand All @@ -54,72 +60,89 @@ const InitAvalanche = async () => {
await avalanche.fetchNetworkSettings()
pchain = avalanche.PChain()
pKeychain = pchain.keyChain()
pKeychain.importKey(privKey)
pKeychain.importKey(privKey1)
pKeychain.importKey(privKey2)
pAddresses = pchain.keyChain().getAddresses()
pAddressStrings = pchain.keyChain().getAddressStrings()
fee = pchain.getDefaultTxFee()

xchain = avalanche.XChain()
xChainBlockchainID = avalanche.getNetwork().X.blockchainID
xKeychain = xchain.keyChain()
xKeychain.importKey(privKey)
xKeychain.importKey(privKey1)
xAddressStrings = xchain.keyChain().getAddressStrings()
}

const main = async (): Promise<any> => {
await InitAvalanche()

try {
const platformVMUTXOResponse: any = await pchain.getUTXOs([msigAlias])
const utxoSet: UTXOSet = platformVMUTXOResponse.utxos
const unsignedTx: UnsignedTx = await pchain.buildExportTx(
utxoSet,
new BN(1000000000),
xChainBlockchainID,
xAddressStrings,
[msigAlias],
[msigAlias],
memo,
asOf,
locktime,
threshold
)
// We need the keychain for signing
const keyPair = pKeychain.getKey(pAddresses[0])

/**
* We assume that only ins UTXOs are selected which are owned by this msig alias.
* If there would be combinations / nesting, we would have to adjust sigIndices
*/

// Create the hash from the tx
const txbuff = unsignedTx.toBuffer()
const msg: Buffer = Buffer.from(
createHash("sha256").update(txbuff).digest()
)
// The signature
const signature = keyPair.sign(msg)

// MultiSigKeyChain
const msigAliasBuffer = pchain.parseAddress(msigAlias)
var msSet: MultiSigAliasSet = new Map([
[msigAliasBuffer.toString(), new OutputOwners(pAddresses, undefined, 1)]
])

const msKeyChain = new MultiSigKeyChain(
msSet,
msg,
avalanche.getHRP(),
PChainAlias
)
msKeyChain.addKey(new MultiSigKeyPair(msKeyChain, pAddresses[0], signature))

const tx: Tx = unsignedTx.sign(msKeyChain)
const txid: string = await pchain.issueTx(tx)
console.log(`Success! TXID: ${txid}`)
for (const msigAlias of msigAliasArray) {
const platformVMUTXOResponse: any = await pchain.getUTXOs([msigAlias])
const utxoSet: UTXOSet = platformVMUTXOResponse.utxos
const unsignedTx: UnsignedTx = await pchain.buildExportTx(
utxoSet,
new BN(1000000000),
xChainBlockchainID,
xAddressStrings,
[msigAlias],
[msigAlias],
memo,
asOf,
locktime,
threshold
)

// Create MultiSig resolver which resolves all aliases
// If you provide addresses, no wildcard sigIndices are created

// MultiSigAliasSet
const msigAliasBuffer = pchain.parseAddress(msigAlias)
const owner = await pchain.getMultisigAlias(msigAlias)

var msSet = new MultisigAliasSet(
new Map([
[
msigAliasBuffer.toString("hex"),
new OutputOwners(
owner.addresses.map((a) => bintools.parseAddress(a, "P")),
new BN(owner.locktime),
owner.threshold
)
]
]),
new Set(pAddresses.map((a) => a.toString("hex")))
)
// Note: inplace modifying of input indices
unsignedTx.getTransaction().resolveMultisigIndices(msSet)

// Create the hash from the tx
const txbuff = unsignedTx.toBuffer()
const msg: Buffer = Buffer.from(
createHash("sha256").update(txbuff).digest()
)

const msKeyChain = new MultisigKeyChain(
msg,
avalanche.getHRP(),
PChainAlias
)

for (const address of pAddresses) {
// We need the keychain for signing
const keyPair = pKeychain.getKey(address)
// The signature
const signature = keyPair.sign(msg)
msKeyChain.addKey(new MultisigKeyPair(msKeyChain, address, signature))
}

// Sign the transaction with msig keychain and issue
const tx: Tx = unsignedTx.sign(msKeyChain)
const txid: string = await pchain.issueTx(tx)
console.log(`Success! TXID: ${txid}`)
}
} catch (e: any) {
console.log(e)
}
}

main()
30 changes: 21 additions & 9 deletions src/apis/platformvm/addsubnetvalidatortx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import BinTools from "../../utils/bintools"
import { PlatformVMConstants } from "./constants"
import { TransferableOutput } from "./outputs"
import { TransferableInput } from "./inputs"
import { Credential, SigIdx, Signature } from "../../common/credentials"
import { Credential, MultisigAliasSet, SigIdx, Signature } from "../../common"
import { BaseTx } from "./basetx"
import { DefaultNetworkID } from "../../utils/constants"
import { Serialization, SerializedEncoding } from "../../utils/serialization"
Expand Down Expand Up @@ -210,12 +210,21 @@ export class AddSubnetValidatorTx extends BaseTx {
}

/**
* Returns the array of [[SigIdx]] for this [[Input]]
* Returns the array of [[SigIdx]] for this [[TX]]
*/
getSigIdxs(): SigIdx[] {
return this.sigIdxs
}

/**
* Sets the array of [[SigIdx]] for this [[TX]]
*/
setSigIdxs(sigIdxs: SigIdx[]) {
this.sigIdxs = sigIdxs
this.sigCount.writeUInt32BE(this.sigIdxs.length, 0)
this.subnetAuth.setAddressIndices(sigIdxs.map((idx) => idx.toBuffer()))
}

getCredentialID(): number {
return PlatformVMConstants.SECPCREDENTIAL
}
Expand All @@ -233,18 +242,21 @@ export class AddSubnetValidatorTx extends BaseTx {
const sigidxs: SigIdx[] = this.getSigIdxs()
const cred: Credential = SelectCredentialClass(this.getCredentialID())
for (let i: number = 0; i < sigidxs.length; i++) {
const keypairs: KeyPair[] = kc.getKeys(sigidxs[`${i}`].getSource())
keypairs.forEach((keypair) => {
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
})
const keypair: KeyPair = kc.getKey(sigidxs[`${i}`].getSource())
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
}
creds.push(cred)
return creds
}

resolveMultisigIndices(resolver: MultisigAliasSet) {
super.resolveMultisigIndices(resolver)
this.setSigIdxs(resolver.resolveMultisig(this.sigIdxs))
}

/**
* Class representing an unsigned AddSubnetValidator transaction.
*
Expand Down
10 changes: 6 additions & 4 deletions src/apis/platformvm/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import { Buffer } from "buffer/"
import BN from "bn.js"
import AvalancheCore from "../../camino"
import { RequestResponseData } from "../../common/apibase"
import { JRPCAPI } from "../../common/jrpcapi"
import { OutputOwners } from "../../common/output"
import {
JRPCAPI,
OutputOwners,
RequestResponseData,
ZeroBN
} from "../../common"

import {
ErrorResponseObject,
Expand Down Expand Up @@ -86,7 +89,6 @@ import { Spender } from "./spender"
const bintools: BinTools = BinTools.getInstance()
const serialization: Serialization = Serialization.getInstance()

const ZeroBN: BN = new BN(0)
const NanoBN = new BN(1000000000)
const rewardPercentDenom = 1000000

Expand Down
14 changes: 5 additions & 9 deletions src/apis/platformvm/basetx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,11 @@ export class BaseTx extends StandardBaseTx<SignerKeyPair, SignerKeyChain> {
)
const sigidxs: SigIdx[] = this.ins[`${i}`].getInput().getSigIdxs()
for (let j: number = 0; j < sigidxs.length; j++) {
const keypairs: SignerKeyPair[] = kc.getKeys(
sigidxs[`${j}`].getSource()
)
keypairs.forEach((keypair) => {
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
})
const keypair: SignerKeyPair = kc.getKey(sigidxs[`${j}`].getSource())
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
}
creds.push(cred)
}
Expand Down
30 changes: 21 additions & 9 deletions src/apis/platformvm/createchaintx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import BinTools from "../../utils/bintools"
import { PlatformVMConstants } from "./constants"
import { TransferableOutput } from "./outputs"
import { TransferableInput } from "./inputs"
import { Credential, SigIdx, Signature } from "../../common/credentials"
import { Credential, MultisigAliasSet, SigIdx, Signature } from "../../common"
import { BaseTx } from "./basetx"
import { DefaultNetworkID } from "../../utils/constants"
import { Serialization, SerializedEncoding } from "../../utils/serialization"
Expand Down Expand Up @@ -245,12 +245,21 @@ export class CreateChainTx extends BaseTx {
}

/**
* Returns the array of [[SigIdx]] for this [[Input]]
* Returns the array of [[SigIdx]] for this [[TX]]
*/
getSigIdxs(): SigIdx[] {
return this.sigIdxs
}

/**
* Set the array of [[SigIdx]] for this [[TX]]
*/
setSigIdxs(sigIdxs: SigIdx[]) {
this.sigIdxs = sigIdxs
this.sigCount.writeUInt32BE(this.sigIdxs.length, 0)
this.subnetAuth.setAddressIndices(this.sigIdxs.map((s) => s.toBuffer()))
}

getCredentialID(): number {
return PlatformVMConstants.SECPCREDENTIAL
}
Expand All @@ -268,18 +277,21 @@ export class CreateChainTx extends BaseTx {
const sigidxs: SigIdx[] = this.getSigIdxs()
const cred: Credential = SelectCredentialClass(this.getCredentialID())
for (let i: number = 0; i < sigidxs.length; i++) {
const keypairs: KeyPair[] = kc.getKeys(sigidxs[`${i}`].getSource())
keypairs.forEach((keypair) => {
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
})
const keypair: KeyPair = kc.getKey(sigidxs[`${i}`].getSource())
const signval: Buffer = keypair.sign(msg)
const sig: Signature = new Signature()
sig.fromBuffer(signval)
cred.addSignature(sig)
}
creds.push(cred)
return creds
}

resolveMultisigIndices(resolver: MultisigAliasSet) {
super.resolveMultisigIndices(resolver)
this.setSigIdxs(resolver.resolveMultisig(this.sigIdxs))
}

/**
* Class representing an unsigned CreateChain transaction.
*
Expand Down
Loading