Skip to content

Instantly share code, notes, and snippets.

@wanderer
Created August 10, 2015 14:19
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 wanderer/de5badbb055a62b71fcc to your computer and use it in GitHub Desktop.
Save wanderer/de5badbb055a62b71fcc to your computer and use it in GitHub Desktop.
var async = require('async')
var VM = require('ethereumjs-vm')
var utils = require('ethereumjs-util')
var Block = require('ethereumjs-block')
var Account = require('ethereumjs-account')
var Tx = require('ethereumjs-tx')
var rlp = utils.rlp
var accountAddress = 'cd2a3d9f938e13cd947ec05abc7fe734df8dd826'
var accountKey = 'cow'
var vm, account
async.series([
createVM,
//watchLog,
createAccount.bind(null, accountAddress),
sendTx,
printVM
], function(err) {
if (err) console.error(err)
else console.log('done!')
})
function createVM(cb) {
vm = new VM()
cb(null)
}
function createAccount(address, cb) {
account = new Account()
account.balance = 'f00000000000000001'
vm.trie.put(new Buffer(address, 'hex'), account.serialize(), cb)
}
function sendTx(cb) {
var tx = new Tx()
tx.to = new Buffer('cd2a3d9f938e13cd947ec05abc7fe734df8dd825', 'hex')
tx.value = 1000000
tx.sign(new Buffer(utils.sha3(accountKey), 'hex'))
var block = new Block({
header: {
coinbase: new Buffer(accountAddress, 'hex'),
gasLimit: 1000000000,
number: 0,
timestamp: new Buffer(pad(Date.now().toString(16)), 'hex')
},
transactions: [ tx.serialize() ],
uncleHeaders: []
})
vm.runBlock({ block: block, generate: true }, cb)
}
function printVM(cb) {
var stream = vm.trie.createReadStream()
stream.on('data', function(data) {
var account = new Account(data.value)
account.getCode(vm.trie, function(err, code) {
console.log(data.key.toString('hex') + ' => ' + code.toString('hex'))
readStorage(account)
})
function readStorage(raw) {
if (raw.stateRoot.toString('hex') === this.SHA3_RLP_NULL) return
var strie = vm.trie.copy()
strie.root = raw.stateRoot
var stream = strie.createReadStream()
stream.on('data', function(data) {
console.log(data.key.toString('hex') + ' ==> ' + rlp.decode(data.value).toString('hex'))
})
}
})
}
function watchLog(vm, cb) {
vm.logReadStream().on('data', function(data) {
console.log(data)
})
cb(null, vm)
}
function pad(str) {
return str.length % 2 === 0 ? str : '0' + str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment