ethereumjs-util#keccak256 TypeScript Examples
The following examples show how to use
ethereumjs-util#keccak256.
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: merkleTree.ts From index-coop-smart-contracts with Apache License 2.0 | 6 votes |
static combinedHash(first: Buffer, second: Buffer): Buffer {
if (!first) {
return second;
}
if (!second) {
return first;
}
return keccak256(MerkleTree.sortAndConcat(first, second));
}
Example #2
Source File: impl-address.ts From openzeppelin-upgrades with MIT License | 6 votes |
/**
* Gets the implementation address from the beacon using its implementation() function.
* @param provider
* @param beaconAddress
* @returns The implementation address.
* @throws {InvalidBeacon} If the implementation() function could not be called or does not return an address.
*/
export async function getImplementationAddressFromBeacon(
provider: EthereumProvider,
beaconAddress: string,
): Promise<string> {
const implementationFunction = '0x' + keccak256(Buffer.from('implementation()')).toString('hex').slice(0, 8);
let result: string | undefined;
try {
const implAddress = await call(provider, beaconAddress, implementationFunction);
result = parseAddress(implAddress);
} catch (e: any) {
if (
!(
e.message.includes('function selector was not recognized') ||
e.message.includes('invalid opcode') ||
e.message.includes('revert')
)
) {
throw e;
} // otherwise fall through with no result
}
if (result === undefined) {
throw new InvalidBeacon(`Contract at ${beaconAddress} doesn't look like a beacon`);
}
return result;
}
Example #3
Source File: version.ts From openzeppelin-upgrades with MIT License | 6 votes |
export function hashBytecode(bytecode: string, constructorArgs = ''): string {
bytecode = bytecode
.replace(/__\$([0-9a-fA-F]{34})\$__/g, (_, placeholder) => `000${placeholder}000`)
.replace(/__\w{36}__/g, placeholder => keccak256(Buffer.from(placeholder)).toString('hex', 0, 20));
// Fail if bytecode is still not valid hex after transformations above.
// Buffer.from silently truncates at the first non-hex character.
// NOTE: Some bytecode seems to have odd length, so we cannot do ([0-9a-fA-F]{2})*
if (!/^(0x)?[0-9a-fA-F]*$/.test(bytecode)) {
throw new Error('Bytecode is not a valid hex string');
}
if (!/^(0x)?[0-9a-fA-F]*$/.test(constructorArgs)) {
throw new Error('Constructor arguments are not a valid hex string');
}
const buf = Buffer.concat([
Buffer.from(bytecode.replace(/^0x/, ''), 'hex'),
Buffer.from(constructorArgs.replace(/^0x/, ''), 'hex'),
]);
return keccak256(buf).toString('hex');
}
Example #4
Source File: utils.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 6 votes |
export function emptyTransactionsRoot(): Buffer {
return keccak256(rlp.encode(''));
}
Example #5
Source File: merkle.ts From bal-mining-scripts with GNU General Public License v3.0 | 6 votes |
combinedHash(first, second) {
if (!first) {
return second;
}
if (!second) {
return first;
}
return keccak256(this.sortAndConcat(first, second));
}
Example #6
Source File: merkleTree.ts From balancer-v2-monorepo with GNU General Public License v3.0 | 6 votes |
combinedHash(first: string, second: string): Buffer | String {
if (!first) {
return second;
}
if (!second) {
return first;
}
return keccak256(this.sortAndConcat(first, second));
}
Example #7
Source File: merkle-tree.ts From merkle-distributor with MIT License | 6 votes |
static combinedHash(first: Buffer, second: Buffer): Buffer {
if (!first) {
return second
}
if (!second) {
return first
}
return keccak256(MerkleTree.sortAndConcat(first, second))
}
Example #8
Source File: index.ts From ethereum-sdk with MIT License | 6 votes |
export function getAuctionHash(
ethereum: Maybe<Ethereum>,
config: EthereumConfig,
auctionId: BigNumber,
): string {
if (!ethereum) {
throw new Error("Wallet is undefined")
}
const hash = ethereum.encodeParameter(AUCTION_HASH_TYPE, {
contractAddress: config.auction,
auctionId: auctionId,
})
return `0x${keccak256(Buffer.from(hash.substring(2), "hex")).toString("hex")}`
}
Example #9
Source File: hash-legacy-order.ts From ethereum-sdk with MIT License | 6 votes |
export function hashLegacyOrder(ethereum: Ethereum, order: SimpleOrder): string {
if (order.type !== "RARIBLE_V1") {
throw new Error(`Not supported type: ${order.type}`)
}
const data = order.data
if (data.dataType !== "LEGACY") {
throw new Error(`Not supported data type: ${data.dataType}`)
}
const makeType = toLegacyAssetType(order.make.assetType)
const takeType = toLegacyAssetType(order.take.assetType)
const struct = {
key: {
owner: order.maker,
salt: order.salt,
sellAsset: makeType,
buyAsset: takeType,
},
selling: order.make.value,
buying: order.take.value,
sellerFee: data.fee,
}
const encodedOrder = ethereum.encodeParameter({ Order: ORDER }, struct)
return `0x${keccak256(Buffer.from(encodedOrder.substring(2), "hex")).toString("hex")}`
}
Example #10
Source File: eip-1967.ts From openzeppelin-upgrades with MIT License | 5 votes |
export function toFallbackEip1967Hash(label: string): string {
return '0x' + keccak256(Buffer.from(label)).toString('hex');
}
Example #11
Source File: eip-1967.ts From openzeppelin-upgrades with MIT License | 5 votes |
export function toEip1967Hash(label: string): string {
const hash = keccak256(Buffer.from(label));
const bigNumber = new BN(hash).sub(new BN(1));
return '0x' + bigNumber.toString(16);
}
Example #12
Source File: verify-proxy.ts From openzeppelin-upgrades with MIT License | 5 votes |
/**
* Gets the txhash that created the contract at the given address, by calling the
* Etherscan API to look for an event that should have been emitted during construction.
*
* @param address The address to get the creation txhash for.
* @param topic The event topic string that should have been logged.
* @param etherscanApi The Etherscan API config
* @returns The txhash corresponding to the logged event, or undefined if not found or if
* the address is not a contract.
* @throws {UpgradesError} if the Etherscan API returned with not OK status
*/
async function getContractCreationTxHash(
address: string,
topic: string,
etherscanApi: EtherscanAPIConfig,
): Promise<any> {
const params = {
module: 'logs',
action: 'getLogs',
fromBlock: '0',
toBlock: 'latest',
address: address,
topic0: '0x' + keccak256(Buffer.from(topic)).toString('hex'),
};
const responseBody = await callEtherscanApi(etherscanApi, params);
if (responseBody.status === RESPONSE_OK) {
const result = responseBody.result;
return result[0].transactionHash; // get the txhash from the first instance of this event
} else if (responseBody.message === 'No records found') {
debug(`no result found for event topic ${topic} at address ${address}`);
return undefined;
} else {
throw new UpgradesError(
`Failed to get logs for contract at address ${address}.`,
() => `Etherscan returned with message: ${responseBody.message}, reason: ${responseBody.result}`,
);
}
}
Example #13
Source File: id.ts From ethereum-sdk with MIT License | 5 votes |
export function id32(value: string): Word {
return toWord(`0x${keccak256(Buffer.from(value)).toString("hex")}`)
}
Example #14
Source File: is-signer.ts From ethereum-sdk with MIT License | 5 votes |
function getEthSignedMessageHash(hash: Buffer): Buffer {
return keccak256(Buffer.concat([Buffer.from(`${START}32`, "ascii"), hash]))
}
Example #15
Source File: database.ts From aurora-relayer with Creative Commons Zero v1.0 Universal | 4 votes |
async eth_sendRawTransaction(
request: any,
transaction: web3.Data
): Promise<web3.Data> {
if (!this.config.writable) {
throw new UnsupportedMethod('eth_sendRawTransaction');
}
const ip = request.ip();
const transactionBytes = Buffer.from(hexToBytes(transaction));
const transactionHash = keccak256(transactionBytes);
// Enforce the EOA blacklist:
let rawTransaction: Transaction | undefined;
try {
rawTransaction = parseRawTransaction(transactionBytes);
// eslint-disable-next-line no-empty
} catch (error) {}
if (rawTransaction?.from) {
const sender = Address.parse(rawTransaction.from).unwrap();
if (this._isBannedEOA(sender)) {
this._banIP(ip, sender.toString());
throw new UnsupportedMethod('eth_sendRawTransaction');
}
}
// Enforce the CA blacklist:
let banReason;
if ((banReason = this._scanForCABans(transaction))) {
this._banIP(ip, banReason);
throw new UnsupportedMethod('eth_sendRawTransaction');
}
const gasPrice = rawTransaction?.gasPrice || 0;
const minGasPrice =
this.config.minGasPrice !== undefined ? this.config.minGasPrice : 0;
if (gasPrice < minGasPrice) {
throw new GasPriceTooLow();
}
return (await this.engine.submit(transactionBytes)).match({
ok: (wrappedSubmitResult) => {
const result = wrappedSubmitResult.submitResult;
// Check if an error occurred
if (result.output().isErr()) {
if (result.result.kind === 'LegacyExecutionResult') {
// legacy SubmitResult just put any error message in the output bytes
throw new RevertError(result.result.output);
} else {
// new versions of SubmitResult carry error information in the status
if (result.result.status.revert) {
throw new RevertError(
result.result.status.revert.output as Uint8Array
);
} else if (result.result.status.outOfFund) {
throw new TransactionError('Out Of Fund');
} else if (result.result.status.outOfGas) {
throw new TransactionError('Out Of Gas');
} else if (result.result.status.outOfOffset) {
throw new TransactionError('Out Of Offset');
} else if (result.result.status.callTooDeep) {
throw new TransactionError('Call Too Deep');
}
}
}
return wrappedSubmitResult.gasBurned || wrappedSubmitResult.tx
? `${bytesToHex(transactionHash)}|${JSON.stringify({
gasBurned: wrappedSubmitResult.gasBurned,
tx: wrappedSubmitResult.tx,
})}`
: bytesToHex(transactionHash);
},
err: (message) => {
const sepIndex = message.lastIndexOf('|');
const code = sepIndex > -1 ? message.substring(0, sepIndex) : message;
if (this.config.errorLog && !code.includes('<html>')) {
const country = request.country();
fs.appendFileSync(
this.config.errorLog,
`${ip}\t${country}\t${code}\n`
);
}
switch (code) {
case 'ERR_INTRINSIC_GAS':
throw new TransactionError('intrinsic gas too low');
case 'ERR_INCORRECT_NONCE':
case 'ERR_TX_RLP_DECODE':
case 'ERR_UNKNOWN_TX_TYPE':
if (this.bus) {
this.bus.publishError('eth_sendRawTransaction', ip, code);
}
throw new TransactionError(message);
case 'ERR_MAX_GAS': // TODO
case 'Exceeded the maximum amount of gas allowed to burn per contract.':
if (this.bus) {
this.bus.publishError(
'eth_sendRawTransaction',
ip,
'ERR_MAX_GAS'
);
}
if (!request.hasAuthorization()) {
this._banIP(ip, 'ERR_MAX_GAS'); // temporarily heavy ban hammer
}
throw new TransactionError(message);
default: {
if (!code.startsWith('ERR_')) {
throw new UnexpectedError(message);
}
throw new TransactionError(message);
}
}
},
});
}