ethereumjs-util#bufferToHex TypeScript Examples

The following examples show how to use ethereumjs-util#bufferToHex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From multisig-react with MIT License 7 votes vote down vote up
isTxHashSignedWithPrefix = (txHash: string, signature: string, ownerAddress: string): boolean => {
    let hasPrefix
    try {
        const rsvSig = {
            r: Buffer.from(signature.slice(2, 66), 'hex'),
            s: Buffer.from(signature.slice(66, 130), 'hex'),
            v: parseInt(signature.slice(130, 132), 16),
        }
        const recoveredData = ecrecover(Buffer.from(txHash.slice(2), 'hex'), rsvSig.v, rsvSig.r, rsvSig.s)
        const recoveredAddress = bufferToHex(pubToAddress(recoveredData))
        hasPrefix = !sameString(recoveredAddress, ownerAddress)
    } catch (e) {
        hasPrefix = true
    }
    return hasPrefix
}
Example #2
Source File: util.ts    From remix-project with MIT License 7 votes vote down vote up
/**
  * sha3 the given @arg value (left pad to 32 bytes)
  *
  * @param {String} value - value to sha3
  * @return {Object} - return sha3ied value
  */
// eslint-disable-next-line camelcase
export function sha3_256 (value) {
  value = toBuffer(addHexPrefix(value))
  const retInBuffer: Buffer = keccak(setLengthLeft(value, 32))
  return bufferToHex(retInBuffer)
}
Example #3
Source File: util.ts    From remix-project with MIT License 7 votes vote down vote up
/*
  ints: ints: IntArray
*/
export function formatMemory (mem) {
  const hexMem = bufferToHex(mem).substr(2)
  const ret = []
  for (let k = 0; k < hexMem.length; k += 32) {
    const row = hexMem.substr(k, 32)
    ret.push(row)
  }
  return ret
}
Example #4
Source File: util.ts    From remix-project with MIT License 7 votes vote down vote up
export function readFromStorage (slot, storageResolver): Promise<string> {
  const hexSlot = '0x' + normalizeHex(bufferToHex(slot))
  return new Promise((resolve, reject) => {
    storageResolver.storageSlot(hexSlot, (error, slot) => {
      if (error) {
        return reject(error)
      }
      if (!slot) {
        slot = { key: slot, value: '' }
      }
      return resolve(normalizeHex(slot.value))
    })
  })
}
Example #5
Source File: merkleTree.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
getProof(el: Buffer) {
    let idx = this.bufferElementPositionIndex[bufferToHex(el)];

    if (typeof idx !== "number") {
      throw new Error("Element does not exist in Merkle tree");
    }

    return this.layers.reduce((proof, layer) => {
      const pairElement = MerkleTree.getPairElement(idx, layer);

      if (pairElement) {
        proof.push(pairElement);
      }

      idx = Math.floor(idx / 2);

      return proof;
    }, []);
  }
Example #6
Source File: VmProxy.ts    From remix-project with MIT License 6 votes vote down vote up
async txWillProcess (data) {
    this.incr++
    this.processingHash = bufferToHex(data.hash())
    this.vmTraces[this.processingHash] = {
      gas: '0x0',
      return: '0x0',
      structLogs: []
    }
    const tx = {}
    tx['hash'] = this.processingHash
    tx['from'] = toChecksumAddress(data.getSenderAddress().toString())
    if (data.to) {
      tx['to'] = toChecksumAddress(data.to.toString())
    }
    this.processingAddress = tx['to']
    tx['input'] = bufferToHex(data.data)
    tx['gas'] = data.gasLimit.toString(10)
    if (data.value) {
      tx['value'] = data.value.toString(10)
    }
    this.txs[this.processingHash] = tx
    this.txsReceipt[this.processingHash] = tx
    this.storageCache[this.processingHash] = {}
    if (data.to) {
      try {
        const storage = await this.vm.stateManager.dumpStorage(data.to)
        this.storageCache[this.processingHash][tx['to']] = storage
        this.lastProcessedStorageTxHash[tx['to']] = this.processingHash
      } catch (e) {
        console.log(e)
      }
    }
    this.processingIndex = 0
  }
Example #7
Source File: typeConversion.ts    From remix-project with MIT License 6 votes vote down vote up
function convertToString (v) {
  try {
    if (v instanceof Array) {
      const ret = []
      for (const k in v) {
        ret.push(convertToString(v[k]))
      }
      return ret
    } else if (BN.isBN(v) || (v.constructor && v.constructor.name === 'BigNumber')) {
      return v.toString(10)
    } else if (v._isBuffer) {
      return bufferToHex(v)
    } else if (typeof v === 'object') {
      const retObject = {}
      for (const i in v) {
        retObject[i] = convertToString(v[i])
      }
      return retObject
    } else {
      return v
    }
  } catch (e) {
    console.log(e)
    return v
  }
}
Example #8
Source File: txRunnerVM.ts    From remix-project with MIT License 6 votes vote down vote up
runBlockInVm (tx, block, callback) {
    this.getVMObject().vm.runBlock({ block: block, generate: true, skipBlockValidation: true, skipBalance: false, skipNonce: true }).then((results) => {
      const result = results.results[0]
      if (result) {
        const status = result.execResult.exceptionError ? 0 : 1
        result.status = `0x${status}`
      }
      callback(null, {
        result: result,
        transactionHash: bufferToHex(Buffer.from(tx.hash())),
        block,
        tx
      })
    }).catch(function (err) {
      callback(err)
    })
  }
Example #9
Source File: Mapping.ts    From remix-project with MIT License 6 votes vote down vote up
async decodeMappingsLocation (preimages, location, storageResolver) {
    const mapSlot = normalizeHex(bufferToHex(location.slot))
    if (!preimages[mapSlot]) {
      return {}
    }
    const ret = {}
    for (const i in preimages[mapSlot]) {
      const mapLocation = getMappingLocation(i, location.slot)
      const globalLocation = {
        offset: location.offset,
        slot: mapLocation
      }
      ret[i] = await this.valueType.decodeFromStorage(globalLocation, storageResolver)
    }
    return ret
  }
Example #10
Source File: disassembler.ts    From remix-project with MIT License 6 votes vote down vote up
function toString (expr) {
  if (expr.name.slice(0, 4) === 'PUSH') {
    return bufferToHex(expr.pushData)
  } else if (expr.name === 'JUMPDEST') {
    return expr.label + ':'
  } else if (expr.args) {
    return expr.name.toLowerCase() + '(' + expr.args.reverse().map(toString).join(', ') + ')'
  }
  return expr.name.toLowerCase()
}
Example #11
Source File: merkle-tree.ts    From merkle-distributor with MIT License 6 votes vote down vote up
constructor(elements: Buffer[]) {
    this.elements = [...elements]
    // Sort elements
    this.elements.sort(Buffer.compare)
    // Deduplicate elements
    this.elements = MerkleTree.bufDedup(this.elements)

    this.bufferElementPositionIndex = this.elements.reduce<{ [hexElement: string]: number }>((memo, el, index) => {
      memo[bufferToHex(el)] = index
      return memo
    }, {})

    // Create layers
    this.layers = this.getLayers(this.elements)
  }
Example #12
Source File: merkle-tree.ts    From merkle-distributor with MIT License 6 votes vote down vote up
getProof(el: Buffer) {
    let idx = this.bufferElementPositionIndex[bufferToHex(el)]

    if (typeof idx !== 'number') {
      throw new Error('Element does not exist in Merkle tree')
    }

    return this.layers.reduce((proof, layer) => {
      const pairElement = MerkleTree.getPairElement(idx, layer)

      if (pairElement) {
        proof.push(pairElement)
      }

      idx = Math.floor(idx / 2)

      return proof
    }, [])
  }
Example #13
Source File: merkleTree.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
constructor(elements: Buffer[]) {
    this.elements = [...elements];
    // Sort elements
    this.elements.sort(Buffer.compare);
    // Deduplicate elements
    this.elements = MerkleTree.bufDedup(this.elements);

    this.bufferElementPositionIndex = this.elements.reduce<{ [hexElement: string]: number }>((memo, el, index) => {
      memo[bufferToHex(el)] = index;
      return memo;
    }, {});

    // Create layers
    this.layers = this.getLayers(this.elements);
  }
Example #14
Source File: is-signer.test.ts    From ethereum-sdk with MIT License 5 votes vote down vote up
function toRpcSig(v: number, r: Buffer, s: Buffer) {
	return bufferToHex(Buffer.concat([setLengthLeft(r, 32), setLengthLeft(s, 32), toBuffer(v)]))
}
Example #15
Source File: fix-signature.ts    From ethereum-sdk with MIT License 5 votes vote down vote up
function toRpcSig(v: number, r: Buffer, s: Buffer) {
	return bufferToHex(Buffer.concat([setLengthLeft(r, 32), setLengthLeft(s, 32), toBuffer(v)]))
}
Example #16
Source File: is-signer.ts    From ethereum-sdk with MIT License 5 votes vote down vote up
function recover(initialHash: Buffer, signature: Buffer): string {
	const sig = fromRpcSig(signature)
	const [hash, v] = fixHashAndV(sig.v, initialHash)
	return bufferToHex(pubToAddress(ecrecover(hash, v, sig.r, sig.s)))
}
Example #17
Source File: merkleTree.ts    From index-coop-smart-contracts with Apache License 2.0 5 votes vote down vote up
getHexRoot(): string {
    return bufferToHex(this.getRoot());
  }
Example #18
Source File: provider.ts    From hardhat-kms-signer with MIT License 5 votes vote down vote up
private async _getNonce(address: Buffer): Promise<BN> {
    const response = (await this._wrappedProvider.request({
      method: "eth_getTransactionCount",
      params: [bufferToHex(address), "pending"],
    })) as string;

    return rpcQuantityToBN(response);
  }
Example #19
Source File: vm-context.ts    From remix-project with MIT License 5 votes vote down vote up
putContractStorage (address, key, value) {
    this.keyHashes[keccak(key).toString('hex')] = bufferToHex(key)
    return super.putContractStorage(address, key, value)
  }
Example #20
Source File: VmProxy.ts    From remix-project with MIT License 5 votes vote down vote up
getCode (address, cb) {
    address = toChecksumAddress(address)
    this.vm.stateManager.getContractCode(Address.fromString(address)).then((result) => {
      cb(null, bufferToHex(result))
    }).catch((error) => {
      cb(error)
    })
  }
Example #21
Source File: VmProxy.ts    From remix-project with MIT License 5 votes vote down vote up
async txProcessed (data) {
    const lastOp = this.vmTraces[this.processingHash].structLogs[this.processingIndex - 1]
    if (lastOp) {
      lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'DESTRUCT'
    }
    const gasUsed = '0x' + data.gasUsed.toString(16)
    this.vmTraces[this.processingHash].gas = gasUsed
    this.txsReceipt[this.processingHash].gasUsed = gasUsed
    const logs = []
    for (const l in data.execResult.logs) {
      const log = data.execResult.logs[l]
      const topics = []
      if (log[1].length > 0) {
        for (const k in log[1]) {
          topics.push('0x' + log[1][k].toString('hex'))
        }
      } else {
        topics.push('0x')
      }
      logs.push({
        address: '0x' + log[0].toString('hex'),
        data: '0x' + log[2].toString('hex'),
        topics: topics,
        rawVMResponse: log
      })
    }
    this.txsReceipt[this.processingHash].logs = logs
    this.txsReceipt[this.processingHash].transactionHash = this.processingHash
    const status = data.execResult.exceptionError ? 0 : 1
    this.txsReceipt[this.processingHash].status = `0x${status}`

    if (data.createdAddress) {
      const address = data.createdAddress.toString()
      this.vmTraces[this.processingHash].return = toChecksumAddress(address)
      this.txsReceipt[this.processingHash].contractAddress = toChecksumAddress(address)
    } else if (data.execResult.returnValue) {
      this.vmTraces[this.processingHash].return = bufferToHex(data.execResult.returnValue)
    } else {
      this.vmTraces[this.processingHash].return = '0x'
    }
    this.processingIndex = null
    this.processingAddress = null
    this.previousDepth = 0
  }
Example #22
Source File: txResultHelper.ts    From remix-project with MIT License 5 votes vote down vote up
function convertToPrefixedHex (input) {
  if (input === undefined || input === null || isHexString(input)) {
    return input
  } else if (Buffer.isBuffer(input)) {
    return bufferToHex(input)
  }
  return '0x' + input.toString(16)
}
Example #23
Source File: merkle-tree.ts    From merkle-distributor with MIT License 5 votes vote down vote up
getHexRoot(): string {
    return bufferToHex(this.getRoot())
  }
Example #24
Source File: merkleTree.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
getHexRoot() {
    return bufferToHex(this.getRoot());
  }
Example #25
Source File: merkle.ts    From bal-mining-scripts with GNU General Public License v3.0 5 votes vote down vote up
getHexRoot() {
        return bufferToHex(this.getRoot());
    }
Example #26
Source File: workspace.ts    From remix-project with MIT License 4 votes vote down vote up
loadWorkspacePreset = async (template: WorkspaceTemplate = 'remixDefault') => {
  const workspaceProvider = plugin.fileProviders.workspace
  const params = queryParams.get() as UrlParametersType

  switch (template) {
    case 'code-template':
    // creates a new workspace code-sample and loads code from url params.
    try {
      let path = ''; let content
      
      if (params.code) {
        const hash = bufferToHex(keccakFromString(params.code))

        path = 'contract-' + hash.replace('0x', '').substring(0, 10) + '.sol'
        content = atob(params.code)
        await workspaceProvider.set(path, content)
      }
      if (params.url) {
        const data = await plugin.call('contentImport', 'resolve', params.url)

        path = data.cleanUrl
        content = data.content

        try {
          content = JSON.parse(content) as any
          if (content.language && content.language === "Solidity" && content.sources) {
            const standardInput: JSONStandardInput = content as JSONStandardInput
            for (const [fname, source] of Object.entries(standardInput.sources)) {
              await workspaceProvider.set(fname, source.content)
            }
            return Object.keys(standardInput.sources)[0]
          } else {
            await workspaceProvider.set(path, JSON.stringify(content))
          }
        } catch (e) {
          console.log(e)
          await workspaceProvider.set(path, content)
        }
      }
      return path
    } catch (e) {
      console.error(e)
    }
    break

    case 'gist-template':
      // creates a new workspace gist-sample and get the file from gist
      try {
        const gistId = params.gist
        const response: AxiosResponse = await axios.get(`https://api.github.com/gists/${gistId}`)
        const data = response.data as { files: any }

        if (!data.files) {
          return dispatch(displayNotification('Gist load error', 'No files found', 'OK', null, () => { dispatch(hideNotification()) }, null))
        }
        const obj = {}

        Object.keys(data.files).forEach((element) => {
          const path = element.replace(/\.\.\./g, '/')

          obj['/' + 'gist-' + gistId + '/' + path] = data.files[element]
        })
        plugin.fileManager.setBatchFiles(obj, 'workspace', true, (errorLoadingFile) => {
          if (errorLoadingFile) {
            dispatch(displayNotification('', errorLoadingFile.message || errorLoadingFile, 'OK', null, () => {}, null))
          }
        })
      } catch (e) {
        dispatch(displayNotification('Gist load error', e.message, 'OK', null, () => { dispatch(hideNotification()) }, null))
        console.error(e)
      }
      break

    default:
      try {
        const templateList = Object.keys(templateWithContent)
        if (!templateList.includes(template)) break
        _paq.push(['trackEvent', 'workspace', 'template', template])
        // @ts-ignore
        const files = await templateWithContent[template]()
        for (const file in files) {
          try {
            await workspaceProvider.set(file, files[file])
          } catch (error) {
            console.error(error)
          }
        }
      } catch (e) {
        dispatch(displayNotification('Workspace load error', e.message, 'OK', null, () => { dispatch(hideNotification()) }, null))
        console.error(e)
      }
      break
  }
}