import assert from 'assert' import { Payload_NodeRegister, Payload_NodeRegisterSynaps, Payload_NodeUpdate } from './abi_system' import { bitmaskArrayToInteger } from './bitmask' // import { privateBlsToPublic, sign } from './sign_bls' import { serializeToBuffer } from './structs' import { bufferToNum, createHashSha256, numToBuffer } from './utils-buffer' import { getPublicKeyBuffer, privateKeyToKeypair } from './wallet' import { MerkleTree } from 'merkletreejs' import { Big, RoundingMode, roundUp } from 'big.js' import { IFields } from './abi_structs' // export interface INodeRegisterSynaps { // rawRequest: string // // this should be the Ethereum signature and will be converted in function // signatureOnRawRequest: string // website: string // producerServerJurisdiction: number | string // } // export const nodeRegisterSynapsKYB = ( // objRegister: INodeRegisterSynaps, // address: string, // publicKey: string | Buffer, // keyBls: string | Buffer, // sessionId: number | string // ) => { // const hexPublicKey = typeof publicKey === 'string' ? publicKey : publicKey.toString('hex') // const hexBls = typeof keyBls === 'string' ? keyBls : keyBls.toString('hex') // // derive the keys from secret // const publicKeyBuf = getPublicKeyBuffer(hexPublicKey, true) // const publicKeyBls = privateBlsToPublic(hexBls) // // build the message to bls sign // const hash = getSynapsMessageHash(address, publicKeyBuf, publicKeyBls, sessionId) // // FOR TESTING ONLY // // const hash = createHashSha256(Buffer.concat([numToBuffer(3, 32).reverse(), Buffer.from('pop', 'utf8')])) // // sign it with bls // const pk_to_num = bufferToNum(Buffer.from(hexBls, 'hex')) // const sk = BigInt(pk_to_num) // const signatureBls = sign(sk, hash) // // serialize with abi to create transaction // const abi = Payload_NodeRegisterSynaps // const trx = serializeToBuffer( // { // ...objRegister, // invocationByte: 1, // signatureOnRawRequest: convertSignatureEthereumToPartisia(objRegister.signatureOnRawRequest).toString('hex'), // producerPublicKey: publicKeyBuf.toString('hex'), // producerBlsKey: publicKeyBls.toString('hex'), // popSignature: signatureBls.toString('hex'), // }, // ...abi // ) // return trx // } // export const getSynapsMessageHash = (address: string, publicKeyBuf: Buffer, publicKeyBls: Buffer, sessionId: number | string) => { // // build the message to bls sign // const message = Buffer.concat([Buffer.from(address, 'hex'), publicKeyBuf, publicKeyBls, numToBuffer(sessionId, 64).reverse()]) // const hash = createHashSha256(message) // return hash // } // export interface INodeRegister { // // id: number | string; // name: string // website: string // streetAddress: string // jurisdictionEntity: number | string // jurisdictionServer: number | string // } // const nodeRegister = (objRegister: INodeRegister, address: string, publicKey: string | Buffer, keyBls: string | Buffer, sessionId = 1) => { // const hexPublicKey = typeof publicKey === 'string' ? publicKey : publicKey.toString('hex') // const hexBls = typeof keyBls === 'string' ? keyBls : keyBls.toString('hex') // // derive the keys from secret // const publicKeyBuf = getPublicKeyBuffer(hexPublicKey, true) // const publicKeyBls = privateBlsToPublic(hexBls) // // build the message to bls sign // const message = Buffer.concat([Buffer.from(address, 'hex'), publicKeyBuf, publicKeyBls, numToBuffer(sessionId, 64).reverse()]) // const hash = createHashSha256(message) // // sign it with bls // const pk_to_num = bufferToNum(Buffer.from(hexBls, 'hex')) // const sk = BigInt(pk_to_num) // const signatureBls = sign(sk, hash) // // serialize with abi to create transaction // const abi = Payload_NodeRegister // const trx = serializeToBuffer( // { // ...objRegister, // invocationByte: 0, // publicKey: publicKey.toString('hex'), // publicKeyBls: publicKeyBls.toString('hex'), // signatureBls: signatureBls.toString('hex'), // }, // ...abi // ) // return trx // } // const nodeUpdate = (objRegister: INodeRegister) => { // return serializeToBuffer({ invocationByte: 5, ...objRegister }, ...Payload_NodeUpdate) // } const byocWithdraw = (ethereumAddress: string | Buffer, amount: string | number | Buffer) => { const bufAddress = typeof ethereumAddress === 'string' ? Buffer.from(ethereumAddress.replace('0x', ''), 'hex') : ethereumAddress assert(bufAddress.length === 20, 'Invalid ETH address') const bufAmount = Buffer.isBuffer(amount) ? amount : numToBuffer(amount, 32 * 8).reverse() assert(bufAmount.length === 32, 'Invalid ETH amount') // serialize with abi to create transaction return Buffer.from([].concat(...[Buffer.from([0]), bufAddress, bufAmount].map((b) => b.toJSON().data))) } const byocEthereumWithdrawBridge = (arySig: string[]): { signatures: string; bitmask: number } => { const aryIdx = [] const arySigEth = [] // get the first two non null signatures for (let i = 0; i < arySig.length; i++) { const sig = arySig[i] aryIdx.push(sig == null ? false : true) if (aryIdx[aryIdx.length - 1]) { arySigEth.push(sig) } if (arySigEth.length === 2) { break } } assert(aryIdx.reduce((pv, cv, ary) => pv + Number(cv), 0) === 2, 'must have only 2 signatures') const bit = bitmaskArrayToInteger(aryIdx) // remap signatures into ETH format // The signature format on PBC is (recoveryId, R, S) and on eth it is expected as (R, S, recoveryId+27) const arySigFormatted = arySigEth.map((v) => { return convertSignaturePartisiaToEthereum(v) }) return { // combine the two signatures into one long hex string signatures: Buffer.concat(arySigFormatted).toString('hex'), bitmask: bit, } } export const convertSignaturePartisiaToEthereum = (signature: string | Buffer): Buffer => { const buf = typeof signature === 'string' ? Buffer.from(signature, 'hex') : signature assert(buf.length === 65) const rId = buf.slice(0, 1) rId[0] += 27 const R = buf.slice(1, 33) const S = buf.slice(33, 65) return Buffer.concat([R, S, rId]) //`${R.toString('hex')}${S.toString('hex')}${rId.toString('hex')}` } export const convertSignatureEthereumToPartisia = (signature: string | Buffer): Buffer => { const buf = typeof signature === 'string' ? Buffer.from(signature, 'hex') : signature assert(buf.length === 65) const R = buf.slice(0, 32) const S = buf.slice(32, 64) const rId = buf.slice(64, 65) // if the v is 27 or 28 substract 27 to get 0 or 1 if ([27, 28].includes(rId[0])) rId[0] -= 27 return Buffer.concat([rId, R, S]) } export interface ByocWithdrawState { key: string value: { amount: string receiver: { identifier: { data: string } } signatures: string[] } } const Payload_Byoc_Withdraw_Merkle_Leaf: IFields[] = [ { field_name: 'withdrawalNonce', field_type: 'num64' }, { field_name: 'ethAddress', field_type: 'eth_address' }, { field_name: 'amount', field_type: 'num256' }, ] const byocEthereumWithdrawMerkleProof = (args: { withdrawalNonce: number | string; withdraws: ByocWithdrawState[] }) => { const computeWithdrawMinusFee = (amt: number | string) => { // RoundUp always Big.RM = roundUp const WITHDRAW_FEE = '0.001' //'0.1%' return new Big(amt).sub(new Big(amt).times(WITHDRAW_FEE)).toFixed(0) } const { withdrawalNonce, withdraws } = args // The leaves of the tree are all withdrawals encoded as: // `SHA256(withdrawalNonce=8bytes, withdrawalDestination=20bytes, withdrawalAmount=32bytes)` const getLeaf = (withdraw: ByocWithdrawState) => { return serializeToBuffer( { withdrawalNonce: withdraw.key, ethAddress: Buffer.from(withdraw.value.receiver.identifier.data, 'base64').toString('hex'), amount: computeWithdrawMinusFee(withdraw.value.amount), }, ...Payload_Byoc_Withdraw_Merkle_Leaf ) } const leaves = withdraws.map((x) => createHashSha256(getLeaf(x))) const tree = new MerkleTree(leaves, createHashSha256, { sortPairs: true }) const root = tree.getRoot().toString('hex') const withdraw = withdraws.find((x) => x.key == String(withdrawalNonce)) const leaf = createHashSha256(getLeaf(withdraw)) const merkleProf = tree.getProof(leaf) assert(tree.verify(merkleProf, leaf, root), 'problem creating Merkle Proof') const bufMerkle = merkleProf.map((m) => Buffer.from(m.data)) // console.log(Buffer.concat(bufMerkle).toString('hex')) return bufMerkle } // export const Node = { nodeRegister, nodeUpdate, nodeRegisterSynapsKYB } export const Byoc = { byocWithdraw, byocEthereumWithdrawBridge, byocEthereumWithdrawMerkleProof }