Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compare buffers directly #851

Merged
merged 2 commits into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions packages/account/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as rlp from 'rlp'
import { KECCAK256_NULL, KECCAK256_NULL_S, KECCAK256_RLP, defineProperties } from 'ethereumjs-util'
import { KECCAK256_NULL, KECCAK256_RLP, defineProperties } from 'ethereumjs-util'
const Buffer = require('safe-buffer').Buffer

export default class Account {
Expand Down Expand Up @@ -27,21 +27,21 @@ export default class Account {
* Creates a new account object
*
* ~~~
* var data = [
* const data = [
* '0x02', //nonce
* '0x0384', //balance
* '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', //stateRoot
* '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', //codeHash
* ]
* const account = new Account(data)
*
* var data = {
* const data2 = {
* nonce: '0x0',
* balance: '0x03e7',
* stateRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
* codeHash: '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
* }
*
* const account = new Account(data)
* const account2 = new Account(data2)
* ~~~
*
* @param data
Expand Down Expand Up @@ -86,17 +86,15 @@ export default class Account {
* Returns a `Boolean` deteremining if the account is a contract.
*/
isContract(): boolean {
return this.codeHash.toString('hex') !== KECCAK256_NULL_S
return !this.codeHash.equals(KECCAK256_NULL)
}

/**
* Returns a `Boolean` determining if the account is empty.
*/
isEmpty(): boolean {
return (
this.balance.toString('hex') === '' &&
this.nonce.toString('hex') === '' &&
this.codeHash.toString('hex') === KECCAK256_NULL_S
this.balance.length === 0 && this.nonce.length === 0 && this.codeHash.equals(KECCAK256_NULL)
)
}
}
4 changes: 2 additions & 2 deletions packages/account/test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ tape('empty constructor', function (tester) {
const it = tester.test
it('should work', function (t) {
const account = new Account()
t.equal(account.nonce.toString('hex'), '')
t.equal(account.balance.toString('hex'), '')
t.equal(account.nonce.length, 0)
t.equal(account.balance.length, 0)
t.equal(
account.stateRoot.toString('hex'),
'56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
Expand Down
17 changes: 8 additions & 9 deletions packages/block/src/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,10 @@ export class Block {
* Validates the transaction trie
*/
validateTransactionsTrie(): boolean {
const txT = this.header.transactionsTrie.toString('hex')
if (this.transactions.length) {
return txT === this.txTrie.root.toString('hex')
return this.header.transactionsTrie.equals(this.txTrie.root)
} else {
return txT === KECCAK256_RLP.toString('hex')
return this.header.transactionsTrie.equals(KECCAK256_RLP)
}
}

Expand Down Expand Up @@ -177,13 +176,13 @@ export class Block {
/**
* Validates the entire block, throwing if invalid.
*
* @param blockChain - the blockchain that this block wants to be part of
* @param blockchain - the blockchain that this block wants to be part of
*/
async validate(blockChain: Blockchain): Promise<void> {
async validate(blockchain: Blockchain): Promise<void> {
await Promise.all([
this.validateUncles(blockChain),
this.validateUncles(blockchain),
this.genTxTrie(),
this.header.validate(blockChain),
this.header.validate(blockchain),
])

if (!this.validateTransactionsTrie()) {
Expand All @@ -206,13 +205,13 @@ export class Block {
validateUnclesHash(): boolean {
const raw = rlp.encode(this.uncleHeaders.map((uh) => uh.raw))

return keccak256(raw).toString('hex') === this.header.uncleHash.toString('hex')
return keccak256(raw).equals(this.header.uncleHash)
}

/**
* Validates the uncles that are in the block, if any. This method throws if they are invalid.
*
* @param blockChain - the blockchain that this block wants to be part of
* @param blockchain - the blockchain that this block wants to be part of
*/
async validateUncles(blockchain: Blockchain): Promise<void> {
if (this.isGenesis()) {
Expand Down
6 changes: 1 addition & 5 deletions packages/block/test/block.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ tape('[Block]: block functions', function (t) {
const block2 = new Block(undefined, { common: common })
block1.setGenesisParams()
block2.setGenesisParams()
st.strictEqual(
block1.hash().toString('hex'),
block2.hash().toString('hex'),
'block hashes match',
)
st.ok(block1.hash().equals(block2.hash()), 'block hashes match')

st.throws(
function () {
Expand Down
14 changes: 5 additions & 9 deletions packages/block/test/header.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import tape = require('tape')
import Common from '@ethereumjs/common'
import { rlp, toBuffer, zeros, KECCAK256_RLP_S, KECCAK256_RLP_ARRAY_S } from 'ethereumjs-util'
import { rlp, toBuffer, zeros, KECCAK256_RLP, KECCAK256_RLP_ARRAY } from 'ethereumjs-util'
import { BlockHeader } from '../src/header'
import { Block } from '../src/block'

tape('[Block]: Header functions', function (t) {
t.test('should create with default constructor', function (st) {
function compareDefaultHeader(st: tape.Test, header: BlockHeader) {
st.deepEqual(header.parentHash, zeros(32))
st.equal(header.uncleHash.toString('hex'), KECCAK256_RLP_ARRAY_S)
st.ok(header.uncleHash.equals(KECCAK256_RLP_ARRAY))
st.deepEqual(header.coinbase, zeros(20))
st.deepEqual(header.stateRoot, zeros(32))
st.equal(header.transactionsTrie.toString('hex'), KECCAK256_RLP_S)
st.equal(header.receiptTrie.toString('hex'), KECCAK256_RLP_S)
st.ok(header.transactionsTrie.equals(KECCAK256_RLP))
st.ok(header.receiptTrie.equals(KECCAK256_RLP))
st.deepEqual(header.bloom, zeros(256))
st.deepEqual(header.difficulty, Buffer.from([]))
st.deepEqual(header.number, toBuffer(1150000))
Expand Down Expand Up @@ -40,11 +40,7 @@ tape('[Block]: Header functions', function (t) {
const header2 = new BlockHeader(undefined, { common: common })
header1.setGenesisParams()
header2.setGenesisParams()
st.strictEqual(
header1.hash().toString('hex'),
header2.hash().toString('hex'),
'header hashes match',
)
st.ok(header1.hash().equals(header2.hash()), 'header hashes match')

st.throws(
function () {
Expand Down
41 changes: 15 additions & 26 deletions packages/ethash/examples/rawExample.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,29 @@
import Ethash from '../src'
const levelup = require('levelup')
const memdown = require('memdown')

const cacheDB = levelup('', {
db: memdown
})
const level = require('level-mem')

const cacheDB = level()
const ethash = new Ethash(cacheDB)

const verifySubmit = (
const verifySubmit = async (
ethash: Ethash,
number: number,
headerHash: Buffer,
nonce: Buffer,
cb: (hash: Buffer) => void
) => {
console.log(number)
ethash.loadEpoc(number, () => {
console.log('EPOC set')
console.log(ethash.seed!.toString('hex'))
const a = ethash.run(headerHash, nonce)
cb(a.hash)
})
nonce: Buffer
): Promise<Buffer> => {
console.log('Verifying number: ', number)
await ethash.loadEpoc(number)
console.log('EPOC set')
console.log('Seed: ', ethash.seed!.toString('hex'))
const a = ethash.run(headerHash, nonce)
return a.hash
}

const headerHash = Buffer.from(
'0e2887aa1a0668bf8254d1a6ae518927de99e3e5d7f30fd1f16096e2608fe05e',
'hex'
)
const nonce = Buffer.from('e360b6170c229d15', 'hex')

verifySubmit(
ethash,
35414,
headerHash,
Buffer.from('e360b6170c229d15', 'hex'),
(result) => {
console.log(result.toString('hex'))
}
)
verifySubmit(ethash, 35414, headerHash, nonce).then((result) => {
console.log('Result: ', result.toString('hex'))
})
2 changes: 1 addition & 1 deletion packages/vm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Currently supported EIPs are:

```javascript
const BN = require('bn.js')
var VM = require('@ethereumjs/vm').default
const VM = require('@ethereumjs/vm').default

// Create a new VM instance
// For explicity setting the HF use e.g. `new VM({ hardfork: 'petersburg' })`
Expand Down
17 changes: 10 additions & 7 deletions packages/vm/examples/decode-opcodes/index.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
const opcodes = require('../../dist/evm/opcodes').lookupOpInfo
const Common = require('@ethereumjs/common').default
const { getOpcodesForHF } = require('../../dist/evm/opcodes')

const opcodes = getOpcodesForHF(new Common('mainnet', 'istanbul'))

const data =
'6107608061000e6000396000f30060003560e060020a90048063141961bc1461006e57806319ac74bd146100cf578063278ecde1146100e75780632c0f7b6f146100f8578063a87430ba1461010a578063ac273aa21461011f578063c06f4c1d14610133578063c1cbbca714610159578063e11523431461016a57005b610079600435610183565b8b6000528a60205289600160a060020a031660405288600160a060020a0316606052876080528660a0528560c0528460e05283610100528261012052816101405280600160a060020a0316610160526101806000f35b6100dd6004356024356106e8565b8060005260206000f35b6100f2600435610454565b60006000f35b61010061017c565b8060005260206000f35b6101156004356101da565b8060005260206000f35b61012d600435602435610729565b60006000f35b61015360043560243560443560643560843560a43560c43560e4356101ee565b60006000f35b610164600435610302565b60006000f35b6101756004356105dd565b60006000f35b5b60005481565b5b6000526001602052604060002080549080600101549080600201549080600301549080600401549080600501549080600601549080600701549080600801549080600901549080600c01549080600d015490508c565b5b600052600260205260406000208054905081565b600060006000600060008811801561020557504287115b61020e576102f4565b600080549081600101905593506001600085815260200190815260200160002092508b83819055508a83600101819055503383600201819055508883600301819055508783600501819055508683600401819055508583600701819055508983600c01819055508483600d01819055506002600033600160a060020a03168152602001908152602001600020915081805490816001019055905083826001016000838152602001908152602001600020819055508333600160a060020a03167f882da991e52c8933ce57314c9ba3f934798d912d862790c40d0feeb7025af08a60006000a35b505050505050505050505050565b600060006000600034116103155761044e565b600160008581526020019081526020016000209250428360040154101561033b5761044d565b82600901805490816001019055915082600a0160008381526020019081526020016000209050338181905550348160010181905550806001015483600601818154019150819055508183600b01600033600160a060020a03168152602001908152602001600020819055508333600160a060020a03167fc5e578961e5bd7481ccf1d1bdfbad97b9f1ddfad520f061ca764a57018f3febe6000866006015481526020016000a3600083600d0154600160a060020a031614156103fc5761044c565b82600d0154600160a060020a03166249f068600060008260e060020a02600052600488815260200133600160a060020a03168152602001348152602001600060008660325a03f161044957005b50505b5b5b50505050565b60006000600160008481526020019081526020016000209150816004015442118015610487575081600501548260060154105b8015610497575060008260060154115b6104a0576105d8565b81600a01600083600b01600033600160a060020a03168152602001908152602001600020548152602001908152602001600020905060008160010154116104e6576105d7565b8054600160a060020a0316600082600101546000600060006000848787f161050a57005b505050806001015482600601818154039150819055508233600160a060020a03167fe139691e7435f1fb40ec50ed3729009226be49087fd00e9e5bac276c2a8f40cf6000846001015481526020016000a360008160010181905550600082600d0154600160a060020a03161415610580576105d6565b81600d0154600160a060020a031663b71f3cde600060008260e060020a0260005260048781526020018554600160a060020a0316815260200185600101548152602001600060008660325a03f16105d357005b50505b5b5b505050565b6000600160008381526020019081526020016000209050806005015481600601541015610609576106e4565b8060030154600160a060020a0316600082600601546000600060006000848787f161063057005b5050508133600160a060020a03167f6be92574b1386f424263a096e8b66ff6cc223ab0f9d18702563aa339a372cf986000846006015481526020016000a36000816006018190555060018160080181905550600081600d0154600160a060020a0316141561069d576106e3565b80600d0154600160a060020a031663484ec26c600060008260e060020a02600052600486815260200185600601548152602001600060008660325a03f16106e057005b50505b5b5050565b600060006002600085600160a060020a0316815260200190815260200160002090508060010160008481526020019081526020016000205491505092915050565b6000600060016000858152602001908152602001600020905080600a0160008481526020019081526020016000209150509291505056'

nameOpCodes(Buffer.from(data, 'hex'))

function nameOpCodes(raw) {
var pushData
let pushData

for (var i = 0; i < raw.length; i++) {
var pc = i
var curOpCode = opcodes(raw[pc], true).name
for (let i = 0; i < raw.length; i++) {
const pc = i
const curOpCode = opcodes[raw[pc]].name

// no destinations into the middle of PUSH
if (curOpCode.slice(0, 4) === 'PUSH') {
var jumpNum = raw[pc] - 0x5f
const jumpNum = raw[pc] - 0x5f
pushData = raw.slice(pc + 1, pc + jumpNum + 1)
i += jumpNum
}
Expand All @@ -28,7 +31,7 @@ function nameOpCodes(raw) {
}

function pad(num, size) {
var s = num + ''
let s = num + ''
while (s.length < size) s = '0' + s
return s
}
Expand Down
6 changes: 3 additions & 3 deletions packages/vm/examples/run-transactions-complete/raw-tx2.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var bidSig = '0x454a2ab3'
var time = '0000000000000000000000000000000000000000000000000000000000000045'
const bidSig = '0x454a2ab3'
const time = '0000000000000000000000000000000000000000000000000000000000000045'

var rawTx2 = {
const rawTx2 = {
nonce: '0x01',
gasPrice: '0x09184e72a000',
gasLimit: '0x20710',
Expand Down
2 changes: 1 addition & 1 deletion packages/vm/lib/evm/eei.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export default class EEI {
*/
async getExternalBalance(address: Buffer): Promise<BN> {
// shortcut if current account
if (address.toString('hex') === this._env.address.toString('hex')) {
if (address.equals(this._env.address)) {
return new BN(this._env.contract.balance)
}

Expand Down
16 changes: 6 additions & 10 deletions packages/vm/lib/evm/opFns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -576,11 +576,7 @@ export const handlers: { [k: string]: OpHandler } = {
PUSH: function (runState: RunState) {
const numToPush = runState.opCode - 0x5f
const loaded = new BN(
runState.eei
.getCode()
.slice(runState.programCounter, runState.programCounter + numToPush)
.toString('hex'),
16,
runState.eei.getCode().slice(runState.programCounter, runState.programCounter + numToPush),
)
runState.programCounter += numToPush
runState.stack.push(loaded)
Expand Down Expand Up @@ -863,9 +859,9 @@ export const handlers: { [k: string]: OpHandler } = {
}

function describeLocation(runState: RunState) {
var hash = keccak256(runState.eei.getCode()).toString('hex')
var address = runState.eei.getAddress().toString('hex')
var pc = runState.programCounter - 1
const hash = keccak256(runState.eei.getCode()).toString('hex')
const address = runState.eei.getAddress().toString('hex')
const pc = runState.programCounter - 1
return hash + '/' + address + ':' + pc
}

Expand Down Expand Up @@ -974,8 +970,8 @@ async function getContractStorage(runState: RunState, address: Buffer, key: Buff

function updateSstoreGas(runState: RunState, found: any, value: Buffer) {
if (runState._common.hardfork() === 'constantinople') {
var original = found.original
var current = found.current
const original = found.original
const current = found.current
if (current.equals(value)) {
// If current value equals new value (this is a no-op), 200 gas is deducted.
runState.eei.useGas(new BN(runState._common.param('gasPrices', 'netSstoreNoopGas')))
Expand Down
2 changes: 1 addition & 1 deletion packages/vm/lib/evm/opcodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ function getFullname(code: number, name: string): string {
/**
* Get suitable opcodes for the required hardfork.
*
* @param common {Common} Ethereumjs Common metadaata object.
* @param common {Common} Ethereumjs Common metadata object.
* @returns {OpcodeList} Opcodes dictionary object.
*/
export function getOpcodesForHF(common: Common): OpcodeList {
Expand Down
2 changes: 1 addition & 1 deletion packages/vm/lib/evm/precompiles/01-ecrecover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function (opts: PrecompileInput): ExecResult {

const data = setLengthRight(opts.data, 128)

var msgHash = data.slice(0, 32)
const msgHash = data.slice(0, 32)
const v = data.slice(32, 64)
const r = data.slice(64, 96)
const s = data.slice(96, 128)
Expand Down
22 changes: 11 additions & 11 deletions packages/vm/lib/evm/precompiles/05-modexp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { OOGResult, ExecResult } from '../evm'
const assert = require('assert')

function multComplexity(x: BN): BN {
var fac1
var fac2
let fac1
let fac2
if (x.lten(64)) {
return x.sqr()
} else if (x.lten(1024)) {
Expand All @@ -23,34 +23,34 @@ function multComplexity(x: BN): BN {
}

function getAdjustedExponentLength(data: Buffer): BN {
var expBytesStart
let expBytesStart
try {
var baseLen = new BN(data.slice(0, 32)).toNumber()
const baseLen = new BN(data.slice(0, 32)).toNumber()
expBytesStart = 96 + baseLen // 96 for base length, then exponent length, and modulus length, then baseLen for the base data, then exponent bytes start
} catch (e) {
expBytesStart = Number.MAX_SAFE_INTEGER - 32
}
var expLen = new BN(data.slice(32, 64))
var firstExpBytes = Buffer.from(data.slice(expBytesStart, expBytesStart + 32)) // first word of the exponent data
const expLen = new BN(data.slice(32, 64))
let firstExpBytes = Buffer.from(data.slice(expBytesStart, expBytesStart + 32)) // first word of the exponent data
firstExpBytes = setLengthRight(firstExpBytes, 32) // reading past the data reads virtual zeros
let firstExpBN = new BN(firstExpBytes)
var max32expLen = 0
let max32expLen = 0
if (expLen.ltn(32)) {
max32expLen = 32 - expLen.toNumber()
}
firstExpBN = firstExpBN.shrn(8 * Math.max(max32expLen, 0))

var bitLen = -1
let bitLen = -1
while (firstExpBN.gtn(0)) {
bitLen = bitLen + 1
firstExpBN = firstExpBN.ushrn(1)
}
var expLenMinus32OrZero = expLen.subn(32)
let expLenMinus32OrZero = expLen.subn(32)
if (expLenMinus32OrZero.ltn(0)) {
expLenMinus32OrZero = new BN(0)
}
var eightTimesExpLenMinus32OrZero = expLenMinus32OrZero.muln(8)
var adjustedExpLen = eightTimesExpLenMinus32OrZero
const eightTimesExpLenMinus32OrZero = expLenMinus32OrZero.muln(8)
const adjustedExpLen = eightTimesExpLenMinus32OrZero
if (bitLen > 0) {
adjustedExpLen.iaddn(bitLen)
}
Expand Down
Loading