Created
February 23, 2019 07:56
-
-
Save CaliosD/daf5269f893ada9a2c34d9d3bf53fb25 to your computer and use it in GitHub Desktop.
Some snippets for self testing on local node of IOST blockchain. Hash and signature functions matched with contract. Feel free to use for testing, and feel free to star🌟if it's useful to you. 🚀
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bs58 = require('bs58'); | |
const { SHA3 } = require('sha3') | |
const nacl = require('tweetnacl'); | |
const EC = require('elliptic').ec; | |
const secp = new EC('secp256k1'); | |
const BN = require('bn.js'); | |
const IOST = require('iost') | |
// equals to `IOSTCrypto.sha3(seed)` in contract | |
const hash = (seed) => { | |
let hash = new SHA3(256); | |
let b = hash.update(seed).digest('hex'); | |
let bytes = Buffer.from(b, 'hex') | |
let hashStr = bs58.encode(bytes) | |
return hashStr | |
} | |
const Algorithm = { | |
Ed25519: 2, | |
Secp256k1: 1, | |
}; | |
// sign data with private key | |
// matches with *signature* in `IOSTCrypto.verify("ed25519", IOSTCrypto.sha3(data), signature, pubkey)` | |
// or `IOSTCrypto.verify("secp256k1", IOSTCrypto.sha3(data), signature, pubkey)` in contract | |
const sign = (algo, data, privateKey) => { | |
try { | |
const seckey = bs58.decode(privateKey); | |
const edKP = new IOST.KeyPair(seckey, algo); | |
const h = new SHA3(256); | |
h.update(data); | |
const info = h.digest("binary"); | |
if (algo == Algorithm.Ed25519) { | |
let buffer = Buffer.from(nacl.sign(info, edKP.seckey)).slice(0, 64) | |
let sig = bs58.encode(buffer) | |
console.log("â›± sig: ", sig) | |
return sig | |
} else if (algo == Algorithm.Secp256k1) { | |
const secpKey = secp.keyFromPrivate(edKP.seckey); | |
const sig = secpKey.sign(info); | |
const r = sig.r; | |
const n = new BN("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16); | |
const s = n.sub(sig.s); | |
const b = Buffer.concat([Buffer.from(r.toArray()), Buffer.from(s.toArray())]); | |
const sigS = bs58.encode(b) | |
console.log("â›± sig: ", sigS) | |
return sigS | |
} else { | |
throw "algo type error" | |
} | |
} catch (e) { | |
console.log("😈 error: ", e) | |
} | |
} | |
module.exports = { | |
hash, | |
sign, | |
Algorithm | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment