Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Created October 20, 2022 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgcardona/4f30996ad46b23b1e8aaef4a9cdc84f5 to your computer and use it in GitHub Desktop.
Save cgcardona/4f30996ad46b23b1e8aaef4a9cdc84f5 to your computer and use it in GitHub Desktop.
import {
Avalanche,
Buffer,
BinTools
} from "../../src"
import {
AVMAPI,
KeyChain,
KeyPair
} from "../../src/apis/avm"
import { getPreferredHRP } from "../../src/utils"
import {
PrivateKeyPrefix,
DefaultLocalGenesisPrivateKey
} from "../../src/utils"
import createHash from 'create-hash';
const ip: string = "localhost"
const port: number = 9650
const protocol: string = "http"
const networkID: number = 12345
const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID)
const xchain: AVMAPI = avalanche.XChain()
const xKeychain: KeyChain = xchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
xKeychain.importKey(privKey)
const xAddresses: Buffer[] = xchain.keyChain().getAddresses()
const xAddressStrings: string[] = xchain.keyChain().getAddressStrings()
const bintools = BinTools.getInstance();
const key: KeyPair = xKeychain.getKey(xAddresses[0])
const digestMessage = (msgStr: string) => {
const mBuf: Buffer = Buffer.from(msgStr, 'utf8')
const msgSize: Buffer = Buffer.alloc(4)
msgSize.writeUInt32BE(mBuf.length, 0)
const msgBuf: Buffer = Buffer.from(`\x1AAvalanche Signed Message:\n${msgSize}${msgStr}`, 'utf8')
return createHash('sha256').update(msgBuf).digest()
}
const recover = (msgStr: string, signature: Buffer): string => {
let digest: globalThis.Buffer = digestMessage(msgStr)
let digestBuff: Buffer = Buffer.from(digest.toString('hex'), 'hex')
let hrp: string = getPreferredHRP(networkID)
let keypair: KeyPair = new KeyPair(hrp, 'X')
let pubKey: Buffer = keypair.recover(digestBuff, signature)
let addressBuff: Buffer = keypair.addressFromPublicKey(pubKey)
let address: string = bintools.addressToString(hrp, 'X', addressBuff)
return address
}
const main = async (): Promise<any> => {
console.log(`Address: ${xAddressStrings[0]}`)
const msgStr: string = "From snowflake to Avalanche"
console.log(`Message: ${msgStr}`)
const digest: globalThis.Buffer = digestMessage(msgStr)
const digestHex = digest.toString('hex')
const digestBuff: Buffer = Buffer.from(digestHex, 'hex')
const signed: Buffer = key.sign(digestBuff)
console.log(`Signature: ${bintools.cb58Encode(signed)}`)
console.log("--------------------------")
console.log("Recovering address from message and signature...")
const recoveredAddress: string = recover(msgStr, signed)
console.log(`Address: ${recoveredAddress}`)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment