Last active
February 1, 2018 12:18
-
-
Save l3wi/dfa405c4d37ab94536dab688b239d67f to your computer and use it in GitHub Desktop.
Simple script to validate POW in .js
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 Crypto = require('iota.crypto.js') | |
const IOTA = require('iota.lib.js') | |
const pify = require('pify') | |
const iota = new IOTA({ provider: 'https://nodes.iota.cafe:443' }) | |
// Vars | |
const bundle = | |
'G9QJBOOSY9UDEZZBX9HPEHIOJRLXGCSTIENORDH9KD9SCHOFHJXLIGGVHJZ99VUSUKFZLYVNQEQAHWLGW' | |
/// Validate Pow | |
const validatePow = async (bundleHash, mwm) => { | |
// findTransactionObjects wraps a number of functions. Most | |
// important func is: iota.utils.transactionObject() | |
// This step generates the tx hash of the trytes returned from the network. | |
// So you are not relying on a third party just pasting in a 👌 hash | |
const bundles = await pify(iota.api.findTransactionObjects.bind(iota.api))({ | |
bundles: [bundleHash] | |
}) | |
// Uncomment the below line to make hash invalid (for testing) | |
// bundles[0].nonce = '999999999999999999999999999' | |
////////////// Find MWM of TX //////////// | |
// 1. Map array | |
// 2. Converts the trytes to trits | |
// 3. Reverse the Array (Pow finds a nonce for which the resulting tx hash has a {mwm} of zeros at the end) | |
// 4. Map through the array to find the first index that is not 0 | |
// 5. Saves this new array of indexes | |
const powSlice = bundles.map(tx => | |
Crypto.converter | |
.trits(iota.utils.transactionTrytes(tx).hash) | |
.reverse() | |
.findIndex((trit, i) => trit !== 0) | |
) | |
// Check MWM passed into this function is greater than or = to the length of 0's in tx hash | |
console.log('MWM of txs: ' + powSlice) | |
let pow = powSlice.map(pow => pow >= mwm) | |
// Return result | |
if (pow.includes(false)) { | |
console.log('PoW appears invalid') | |
return false | |
} else { | |
console.log('PoW appears valid') | |
return true | |
} | |
} | |
validatePow(bundle, 14) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment