Skip to content
This repository has been archived by the owner on Dec 5, 2021. It is now read-only.

Commit

Permalink
Added whitelist (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
boyuan-chen authored Jun 4, 2021
1 parent 9a3efd5 commit 06a23d0
Show file tree
Hide file tree
Showing 18 changed files with 266 additions and 69 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ packages/data-transport-layer/db
*.swp

.env
env.js
env.js
env.yml

.serverless
8 changes: 5 additions & 3 deletions ops/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ services:
environment:
FRAUD_PROOF_WINDOW_SECONDS: 0
L1_NODE_WEB3_URL: http://l1_chain:8545
# these keys are hardhat's first 2 accounts, DO NOT use in production
# these keys are hardhat's first 3 accounts, DO NOT use in production
DEPLOYER_PRIVATE_KEY: "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
SEQUENCER_PRIVATE_KEY: "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"
RELAYER_PRIVATE_KEY: "0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a"
# skip compilation when run in docker-compose, since the contracts
# were already compiled in the builder step
NO_COMPILE: 1
Expand Down Expand Up @@ -106,10 +107,11 @@ services:
L1_NODE_WEB3_URL: http://l1_chain:8545
L2_NODE_WEB3_URL: http://l2geth:8545
URL: http://deployer:8081/addresses.json
WHITELIST_ENDPOINT: https://api-message-relayer.rinkeby.omgx.network/get.whitelist
# a funded hardhat account
L1_WALLET_KEY: "0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97"
L1_WALLET_KEY: "0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a"
RETRIES: 60
POLLING_INTERVAL: 500
POLLING_INTERVAL: 1500
GET_LOGS_INTERVAL: 500

batch_submitter:
Expand Down
1 change: 1 addition & 0 deletions packages/contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ npx hardhat deploy \
--ovm-proposer-address ... \
--ovm-relayer-address ... \
--ovm-sequencer-address ... \
--ovm-relayer-address ... \
--scc-fraud-proof-window ... \
--scc-sequencer-publish-window ...
```
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/bin/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import hre from 'hardhat'

const sequencer = new Wallet(process.env.SEQUENCER_PRIVATE_KEY)
const deployer = new Wallet(process.env.DEPLOYER_PRIVATE_KEY)
const relayer = new Wallet(process.env.RELAYER_PRIVATE_KEY)

const main = async () => {

Expand All @@ -35,7 +36,7 @@ const main = async () => {
sccSequencerPublishWindow: config.sccFraudProofWindow,
ovmSequencerAddress: sequencer.address,
ovmProposerAddress: sequencer.address,
ovmRelayerAddress: sequencer.address,
ovmRelayerAddress: relayer.address,
ovmAddressManagerOwner: deployer.address,
noCompile: process.env.NO_COMPILE ? true : false,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ contract OVM_L1CrossDomainMessenger is
**********************/

mapping (bytes32 => bool) public blockedMessages;
address public customRelayer;

/***************
* Constructor *
Expand Down Expand Up @@ -117,6 +118,18 @@ contract OVM_L1CrossDomainMessenger is
__ReentrancyGuard_init_unchained();
}

/**
* @param _customRelayer Address of the Address Manager.
*/
function initializeCustomRelayer(
address _customRelayer
)
public
onlyOwner()
{
customRelayer = _customRelayer;
}

/**
* Pause relaying.
*/
Expand Down Expand Up @@ -298,6 +311,16 @@ contract OVM_L1CrossDomainMessenger is
resolve("OVM_StateCommitmentChain")
);

if (msg.sender == customRelayer) {
return (
ovmStateCommitmentChain.verifyStateCommitment(
_proof.stateRoot,
_proof.stateRootBatchHeader,
_proof.stateRootProof
)
);
}

return (
ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false
&& ovmStateCommitmentChain.verifyStateCommitment(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ const deployFn: DeployFunction = async (hre) => {
// initialize this.
await OVM_L1CrossDomainMessenger.initialize(Lib_AddressManager.address)

// only allow the relayer to relay message
const initializeCustomRelayer = await OVM_L1CrossDomainMessenger.initializeCustomRelayer((hre as any).deployConfig.ovmRelayerAddress)
await initializeCustomRelayer.wait()

const libAddressManager = await OVM_L1CrossDomainMessenger.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ const deployFn: DeployFunction = async (hre) => {

await Proxy__OVM_L1CrossDomainMessenger.initialize(Lib_AddressManager.address)

// only allow the relayer to relay message
const initializeCustomRelayer = await Proxy__OVM_L1CrossDomainMessenger.initializeCustomRelayer((hre as any).deployConfig.ovmRelayerAddress)
await initializeCustomRelayer.wait()

const libAddressManager = await Proxy__OVM_L1CrossDomainMessenger.libAddressManager()
if (libAddressManager !== Lib_AddressManager.address) {
throw new Error(
Expand Down
4 changes: 4 additions & 0 deletions packages/message-relayer/lambda/env.yml.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
ROLE:
SECURITYGROUP:
SUBNET1:
SUBNET2:
29 changes: 29 additions & 0 deletions packages/message-relayer/lambda/serverless.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
service: sls-omgx-rinkeby-message-relayer # NOTE: update this with your service name

provider:
name: aws
runtime: python3.7
stackName: sls-omgx-rinkeby-message-relayer
stage: prod
region: us-east-1
role: ${file(env.yml):ROLE}

package:
exclude:
- .gitignore
individually: true

functions:
get_whitelist:
handler: whitelist.get_whitelist
vpc:
securityGroupIds:
- ${file(env.yml):SECURITYGROUP}
subnetIds:
- ${file(env.yml):SUBNET1}
- ${file(env.yml):SUBNET2}
events:
- http:
path: get.whitelist
method: get
cors: true
21 changes: 21 additions & 0 deletions packages/message-relayer/lambda/whitelist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import json

def get_whitelist(event, context):
whitelist = [
"0x455c31AF3Bb2e3f4300F517bd246E39b4A7f49c5",
]
response = {
"statusCode": 201,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": True,
"Strict-Transport-Security": "max-age=63072000; includeSubdomains; preload",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "same-origin",
"Permissions-Policy": "*",
},
"body": json.dumps(whitelist),
}
return response
1 change: 1 addition & 0 deletions packages/message-relayer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"dotenv": "^8.2.0",
"ethers": "^5.1.0",
"merkletreejs": "^0.2.18",
"node-fetch": "^2.6.1",
"rlp": "^2.2.6"
},
"devDependencies": {
Expand Down
10 changes: 10 additions & 0 deletions packages/message-relayer/src/exec/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ const main = async () => {
const L1_WALLET_KEY = config.str('l1-wallet-key', env.L1_WALLET_KEY)
const MNEMONIC = config.str('mnemonic', env.MNEMONIC)
const HD_PATH = config.str('hd-path', env.HD_PATH)
const WHITELIST_ENDPOINT = config.str(
'whitlist-endpoint',
env.WHITELIST_ENDPOINT
) || ''
const WHITELIST_POLLING_INTERVAL = config.uint(
'whitlist-polling-interval',
parseInt(env.WHITELIST_POLLING_INTERVAL, 10) || 60000
)
const RELAY_GAS_LIMIT = config.uint(
'relay-gas-limit',
parseInt(env.RELAY_GAS_LIMIT, 10) || 4000000
Expand Down Expand Up @@ -82,6 +90,8 @@ const main = async () => {
l2BlockOffset: L2_BLOCK_OFFSET,
l1StartOffset: L1_START_OFFSET,
getLogsInterval: GET_LOGS_INTERVAL,
whitelistEndpoint: WHITELIST_ENDPOINT,
whitelistPollingInterval: WHITELIST_POLLING_INTERVAL,
})

await service.start()
Expand Down
76 changes: 72 additions & 4 deletions packages/message-relayer/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { Contract, ethers, Wallet, BigNumber, providers } from 'ethers'
import * as rlp from 'rlp'
import { MerkleTree } from 'merkletreejs'
import fetch from 'node-fetch';

/* Imports: Internal */
import { fromHexString, sleep } from '@eth-optimism/core-utils'
Expand Down Expand Up @@ -40,6 +41,10 @@ interface MessageRelayerOptions {

// Number of blocks within each getLogs query - max is 2000
getLogsInterval?: number

// whitlist
whitelistEndpoint?: string
whitelistPollingInterval?: number
}

const optionSettings = {
Expand All @@ -49,6 +54,7 @@ const optionSettings = {
l2BlockOffset: { default: 1 },
l1StartOffset: { default: 0 },
getLogsInterval: { default: 2000 },
whitelistPollingInterval: { default: 60000 },
}

export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
Expand All @@ -66,6 +72,8 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
OVM_L1CrossDomainMessenger: Contract
OVM_L2CrossDomainMessenger: Contract
OVM_L2ToL1MessagePasser: Contract
whitelist: Array<String>
lastWhitelistPollingTimestamp: number
}

protected async _init(): Promise<void> {
Expand All @@ -75,6 +83,7 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
pollingInterval: this.options.pollingInterval,
l2BlockOffset: this.options.l2BlockOffset,
getLogsInterval: this.options.getLogsInterval,
whitelistPollingInterval: this.options.whitelistPollingInterval,
})
// Need to improve this, sorry.
this.state = {} as any
Expand Down Expand Up @@ -137,12 +146,15 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
this.state.lastFinalizedTxHeight = this.options.fromL2TransactionIndex || 0
this.state.nextUnfinalizedTxHeight =
this.options.fromL2TransactionIndex || 0
this.state.lastWhitelistPollingTimestamp = 0
}

protected async _start(): Promise<void> {
while (this.running) {
await sleep(this.options.pollingInterval)

await this._getWhitelist();

try {
// Check that the correct address is set in the address manager
const relayer = await this.state.Lib_AddressManager.getAddress(
Expand Down Expand Up @@ -355,11 +367,42 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
this.logger.info('Got state batch header', { header })
}

return true
const size = (await this._getStateBatchHeader(height)).batch.batchSize.toNumber()
const filter = this.state.OVM_L2CrossDomainMessenger.filters.SentMessage()
const events = await this.state.OVM_L2CrossDomainMessenger.queryFilter(
filter,
height + this.options.l2BlockOffset,
height + size + this.options.l2BlockOffset - 1
)

// return !(await this.state.OVM_StateCommitmentChain.insideFraudProofWindow(
// header.batch
// ))
const messages = events.map((event) => {
const message = event.args.message
const decoded = this.state.OVM_L2CrossDomainMessenger.interface.decodeFunctionData(
'relayMessage',
message
)

return {
target: decoded._target,
sender: decoded._sender,
}
})

const insideWhitelist = messages.every(message => this.state.whitelist.includes(message.target))

if (insideWhitelist) {
this.logger.info('Found the batch header in whitelist')
return true
} else {
const insideFPW = await this.state.OVM_StateCommitmentChain.insideFraudProofWindow(header.batch);
if (insideFPW === true) {
this.logger.info('INSIDE FRAUD PRROF WINDOW - BLOCKING TRANSACTION.');
return false;
} else {
this.logger.info('Fraud proof window elapsed.');
return true
}
}
}

/**
Expand Down Expand Up @@ -547,4 +590,29 @@ export class MessageRelayerService extends BaseService<MessageRelayerOptions> {
}
this.logger.info('Message successfully relayed to Layer 1!')
}

private async _getWhitelist(): Promise<Array<String>> {
try {
if (this.options.whitelistEndpoint) {
if (this.state.lastWhitelistPollingTimestamp === 0 ||
new Date().getTime() > this.state.lastWhitelistPollingTimestamp + this.options.whitelistPollingInterval
) {
const response = await fetch(this.options.whitelistEndpoint);
const whitelist = await response.json();
this.state.lastWhitelistPollingTimestamp = new Date().getTime();
this.state.whitelist = whitelist;
this.logger.info('Found the whitelist', { whitelist: whitelist })
} else {
this.logger.info('Loading the whitelist', { whitelist: this.state.whitelist })
return this.state.whitelist;
}
} else {
this.logger.info('The whitelist endpoint was not provided')
this.state.whitelist = [];
}
} catch {
this.logger.info('Failed to fetch the whitelist')
this.state.whitelist = [];
}
}
}
22 changes: 12 additions & 10 deletions packages/omgx/wallet/deployment/local/addresses.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"L1LiquidityPool": "0x86A2EE8FAf9A840F7a2c64CA3d51209F9A02081D",
"L2LiquidityPool": "0x922D6956C99E12DFeB3224DEA977D0939758A1Fe",
"L1ERC20": "0xf953b3A269d80e3eB0F2947630Da976B896A8C5b",
"L2DepositedERC20": "0x1fA02b2d6A771842690194Cf62D91bdd92BfE28d",
"L1ERC20Gateway": "0xAA292E8611aDF267e563f334Ee42320aC96D0463",
"l1ETHGatewayAddress": "0x998abeb3E57409262aE5b751f60747921B33613E",
"l1MessengerAddress": "0x59b670e9fA9D0A427751Af201D676719a970857b",
"L2TokenPool": "0x5c74c94173F05dA1720953407cbb920F3DF9f887",
"AtomicSwap": "0xe8D2A1E88c91DCd5433208d4152Cc4F399a7e91d",
"L2ERC721": "0xfbC22278A96299D91d41C453234d97b4F5Eb9B2d"
"L1LiquidityPool": "0xbdEd0D2bf404bdcBa897a74E6657f1f12e5C6fb6",
"L2LiquidityPool": "0xbdEd0D2bf404bdcBa897a74E6657f1f12e5C6fb6",
"L1ERC20": "0xA7918D253764E42d60C3ce2010a34d5a1e7C1398",
"L2DepositedERC20": "0xA7918D253764E42d60C3ce2010a34d5a1e7C1398",
"L1ERC20Gateway": "0x93C7a6D00849c44Ef3E92E95DCEFfccd447909Ae",
"l1ETHGatewayAddress": "0x4826533B4897376654Bb4d4AD88B7faFD0C98528",
"l1MessengerAddress": "0x4ed7c70F96B99c776995fB64377f0d4aB3B0e1C1",
"L2TokenPool": "0x71a9d115E322467147391c4a71D85F8e1cA623EF",
"AtomicSwap": "0xB737dD8FC9B304A3520B3bb609CC7532F1425Ad0",
"L1Message": "0xDBD6c48913473F648f64d8E9fdDeead1F1734E22",
"L2Message": "0x71a9d115E322467147391c4a71D85F8e1cA623EF",
"L2ERC721": "0xeC406dA90079339a828DE424C9BF5ab58F851eE9"
}
Loading

0 comments on commit 06a23d0

Please sign in to comment.