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

integrate solEVM #195

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
18 changes: 15 additions & 3 deletions contracts/ExitHandler.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import "./IExitHandler.sol";
import "./Bridge.sol";
import "./TxLib.sol";
import "./PriorityQueue.sol";
import "./PlasmaEnforcer.sol";

contract ExitHandler is IExitHandler, DepositHandler {

Expand Down Expand Up @@ -52,6 +53,7 @@ contract ExitHandler is IExitHandler, DepositHandler {
uint256 public exitStake;
uint256 public nftExitCounter;
uint256 public nstExitCounter;
address public plasmaEnforcer;

/**
* UTXO → Exit mapping. Contains exits for both NFT and ERC20 colors
Expand All @@ -78,6 +80,10 @@ contract ExitHandler is IExitHandler, DepositHandler {
exitDuration = _exitDuration;
}

function setPlasmaEnforcer(address _enforcerAddress) public ifAdmin {
plasmaEnforcer = _enforcerAddress;
}

function startExit(
bytes32[] memory _youngestInputProof, bytes32[] memory _proof,
uint8 _outputIndex, uint8 _inputIndex
Expand Down Expand Up @@ -311,8 +317,8 @@ contract ExitHandler is IExitHandler, DepositHandler {
txn = TxLib.parseTx(txData);

// make sure one is spending the other one
require(txHash1 == txn.ins[_inputIndex].outpoint.hash);
require(_outputIndex == txn.ins[_inputIndex].outpoint.pos);
require(txHash1 == txn.ins[_inputIndex].outpoint.hash, "hash does not match");
require(_outputIndex == txn.ins[_inputIndex].outpoint.pos, "outputs do not match");

// if transfer, make sure signature correct
if (txn.txType == TxLib.TxType.Transfer) {
Expand All @@ -323,7 +329,13 @@ contract ExitHandler is IExitHandler, DepositHandler {
txn.ins[_inputIndex].r,
txn.ins[_inputIndex].s
);
require(exits[utxoId].owner == signer);
require(exits[utxoId].owner == signer, "output owner not signer");
} else if (txn.txType == TxLib.TxType.SpendCond) {
// check that transaction whitelisted
uint256 verificationTime = PlasmaEnforcer(plasmaEnforcer).verificationStartTime(txHash);
require(verificationTime > 0, "Transaction not verified");
require(block.timestamp >= verificationTime + (exitDuration / 2), "Transaction still in verification");
// TODO: check that verification came passed.
} else {
revert("unknown tx type");
}
Expand Down
85 changes: 85 additions & 0 deletions contracts/PlasmaEnforcer.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* Copyright (c) 2018-present, Leap DAO (leapdao.org)
*
* This source code is licensed under the Mozilla Public License, version 2,
* found in the LICENSE file in the root directory of this source tree.
*/

pragma solidity 0.5.2;

import "../node_modules/solEVM-enforcer/contracts/Enforcer.sol";
import "./TxLib.sol";
import "./Bridge.sol";

contract PlasmaEnforcer is Enforcer {

Bridge public bridge;

constructor(
address _verifier,
uint256 _challengePeriod,
uint256 _bondAmount,
uint256 _maxExecutionDepth,
address _bridge) public Enforcer(_verifier, _challengePeriod, _bondAmount, _maxExecutionDepth) {
bridge = Bridge(_bridge);
}

/**
* txHash -> Verification Start Time mapping.
* Used to verify consolidate and computation transactions
* before they can be used to challenge exits.
*/

mapping(bytes32 => TxLib.Output) verifications;

function verificationStartTime(bytes32 txHash) public view returns (uint256) {
return verifications[txHash].startTime;
}

/**
* Spending conditions require an interactive game to ensure validity of transaction.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️ comments ftw

* A verification process is introduced with half the duration of the exit procedure.
* During this verification a transaction can be challenged before it is whitelisted
* to be used in an exit challenge. We use this verification process to scrutinize
* the validity of spending conditions.
*/
function startWhitelisting(bytes32[] memory _proof, uint8 _outputIndex, bytes32 _rootHash) public payable {
require(msg.value >= bondAmount, "Not enough ether sent to pay for verification stake");
uint32 timestamp;
(,timestamp) = bridge.periods(_proof[0]);
require(timestamp > 0, "The referenced period was not submitted to bridge");

// check exiting tx inclusion in the root chain block
bytes32 utxoId;
bytes memory txData;
(, utxoId, txData) = TxLib.validateProof(64, _proof);
if (uint256(_rootHash) == 0) {
utxoId = bytes32(uint256(_outputIndex) << 248 | uint248(uint256(utxoId)));
}
require(verifications[utxoId].stake == 0, "Transaction already registered");
TxLib.Tx memory txn = TxLib.parseTx(txData);

if (uint256(_rootHash) > 0) {
// iterate over all inputs
// make sure these inputs have been registered for verification
// fail if not
// if yes, then delete them all and return stakes
uint256 stake = 0;
for (uint i = 0; i < txn.ins.length; i++) {
bytes32 prevUtxoId = txn.ins[i].outpoint.hash;
prevUtxoId = bytes32((uint256(txn.ins[i].outpoint.pos) << 248) | uint248(uint256(txn.ins[i].outpoint.hash)));
WhitelistVerification memory prevVerification = verifications[prevUtxoId];
require(prevVerification.startTime > 0, "Input not found");
stake += prevVerification.stake;

// create array for hashing
delete verifications[prevUtxoId];
}
msg.sender.transfer(stake);
// call register function
}
verifications[utxoId] = WhitelistVerification(uint32(block.timestamp), txn.outs[_outputIndex], msg.value);
emit WhitelistStarted(utxoId);
}

}
8 changes: 4 additions & 4 deletions contracts/PriorityQueue.sol
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ library PriorityQueue {
uint256 currentSize;
}

function insert(Token storage self, uint256 k) internal {
function insert(Token storage self, uint256 k) public {
self.heapList.push(k);
self.currentSize = self.currentSize.add(1);
percUp(self, self.currentSize);
}

function minChild(Token storage self, uint256 i) internal view returns (uint256) {
function minChild(Token storage self, uint256 i) public view returns (uint256) {
if (i.mul(2).add(1) > self.currentSize) {
return i.mul(2);
} else {
Expand All @@ -44,11 +44,11 @@ library PriorityQueue {
}
}

function getMin(Token storage self) internal view returns (uint256) {
function getMin(Token storage self) public view returns (uint256) {
return self.heapList[1];
}

function delMin(Token storage self) internal returns (uint256) {
function delMin(Token storage self) public returns (uint256) {
uint256 retVal = self.heapList[1];
self.heapList[1] = self.heapList[self.currentSize];
delete self.heapList[self.currentSize];
Expand Down
1 change: 0 additions & 1 deletion contracts/Vault.sol
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import "./TransferrableToken.sol";
import "./IERC1948.sol";

contract Vault is Adminable {
using PriorityQueue for PriorityQueue.Token;

// 2**15 + 1
uint16 constant NFT_FIRST_COLOR = 32769;
Expand Down
37 changes: 37 additions & 0 deletions contracts/mocks/VerifierMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
pragma solidity ^0.5.2;
pragma experimental ABIEncoderV2;

import "../../node_modules/solEVM-enforcer/contracts/Enforcer.sol";


contract VerifierMock {
Enforcer enforcer;
uint256 public timeoutDuration;

constructor(uint256 timeout) public {
timeoutDuration = timeout;
}

function setEnforcer(address _enforcer) public {
enforcer = Enforcer(_enforcer);
}

function initGame(
bytes32 executionId,
bytes32 solverHashRoot,
bytes32 challengerHashRoot,
uint256 treeDepth,
bytes32 customEnvironmentHash,
address challenger,
address codeContractAddress,
bytes memory callData
) public returns (bytes32 disputeId) {
// do nothing
}

function submitResult(bytes32 executionId, bool solverWon, address challenger) public {
enforcer.result(executionId, solverWon, challenger);
}

function dummy() public {}
}
4 changes: 4 additions & 0 deletions migrations/3_deploy_plasma.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const NativeToken = artifacts.require('NativeToken');
const PoaOperator = artifacts.require('PoaOperator');
const ExitHandler = artifacts.require('FastExitHandler');
const SwapRegistry = artifacts.require('SwapRegistry');
const PriorityQueue = artifacts.require('PriorityQueue');
const AdminableProxy = artifacts.require('AdminableProxy');
const BridgeProxy = artifacts.require('BridgeProxy');
const OperatorProxy = artifacts.require('OperatorProxy');
Expand Down Expand Up @@ -53,6 +54,9 @@ module.exports = (deployer, network, accounts) => {
data = bridgeCont.contract.methods.initialize(parentBlockInterval).encodeABI();
const bridgeProxy = await deployer.deploy(BridgeProxy, bridgeCont.address, data, { from: admin});

const pqLib = await deployer.deploy(PriorityQueue);
ExitHandler.link('PriorityQueue', pqLib.address);

log(' 🕐 Exit duration:', durationToString(exitDuration));
log(' 💰 Exit stake:', exitStake);

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"openzeppelin-solidity": "=2.1.1",
"pify": "^4.0.1",
"scrypt": "^6.0.3",
"solEVM-enforcer": "https://github.com/leapdao/solEVM-enforcer#master",
"truffle-hdwallet-provider": "1.0.2"
}
}
126 changes: 126 additions & 0 deletions test/plasmaEnforcer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { Tx, Input, Output, Outpoint } from 'leap-core';
import { submitNewPeriodWithTx } from './helpers';

const ethUtil = require('ethereumjs-util');
require('./helpers/setup');

const { BN } = web3.utils;
const PlasmaEnforcer = artifacts.require('./PlasmaEnforcer.sol');
const VerifierMock = artifacts.require('./VerifierMock.sol');
const AdminableProxy = artifacts.require('./AdminableProxy.sol');
const Bridge = artifacts.require('./Bridge.sol');

contract('PlasmaEnforcer', (accounts) => {
const alice = accounts[0];
const alicePriv = '0x278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f';
const bob = accounts[1];
const challengePeriod = 30;
const timeoutDuration = 2;
const maxExecutionDepth = 10;
let enforcer;
let verifier;
let proxy;
let bridge;
const parentBlockInterval = 0;
let depositTx;
let transferTx;
const depositId = 1;
const depositAmount = new BN(100);
const bondAmount = 999;

const submitNewPeriod = txs => submitNewPeriodWithTx(txs, bridge, { from: bob });

before('Prepare contracts', async () => {
const bridgeCont = await Bridge.new();
let data = await bridgeCont.contract.methods.initialize(parentBlockInterval).encodeABI();
proxy = await AdminableProxy.new(bridgeCont.address, data, {from: accounts[2]});
bridge = await Bridge.at(proxy.address);
data = await bridge.contract.methods.setOperator(accounts[1]).encodeABI();
await proxy.applyProposal(data, {from: accounts[2]});



verifier = await VerifierMock.new(timeoutDuration);
enforcer = await PlasmaEnforcer.new(verifier.address, challengePeriod, bondAmount, maxExecutionDepth, bridge.address);

await verifier.setEnforcer(enforcer.address);

depositTx = Tx.deposit(depositId, depositAmount.toNumber(), alice);
transferTx = Tx.transfer(
[new Input(new Outpoint(depositTx.hash(), 0))],
[new Output(50, bob), new Output(50, alice)]
).sign([alicePriv]);
});

it('Should allow to challenge exit by whitelisted tx', async () => {
const conditionScript = Buffer.from('11223344', 'hex');
const scriptHash = ethUtil.ripemd160(conditionScript);

transferTx = Tx.transfer(
[new Input(new Outpoint(depositTx.hash(), 0))],
[new Output(50, alice), new Output(50, alice)]
).sign([alicePriv]);
const spendTx = Tx.transfer(
[new Input(new Outpoint(transferTx.hash(), 1))],
[new Output(25, `0x${scriptHash.toString('hex')}`), new Output(25, alice)]
).sign([alicePriv]);




const spendCondTx = Tx.spendCond(
[
new Input({ // gas input
prevout: new Outpoint(transferTx.hash(), 0),
script: conditionScript,
}),
new Input({ // payload inputs
prevout: new Outpoint(spendTx.hash(), 1),
}),
],
[
new Output(25, alice, 0), // playload output
new Output(45, `0x${scriptHash.toString('hex')}`, 0), // gas change output
]
);
spendCondTx.inputs[0].setMsgData('0xd01a81e1');

const period = await submitNewPeriod([depositTx, transferTx, spendTx, spendCondTx]);

const transferProof = period.proof(transferTx);
const spendProof = period.proof(spendTx);
const condProof = period.proof(spendCondTx);

// withdraw output
// await exitHandler.startExit(transferProof, spendProof, 1, 0, { from: alice });
await enforcer.startWhitelisting(transferProof, 0, '0x', {value: bondAmount});
await enforcer.startWhitelisting(spendProof, 1, '0x', {value: bondAmount});

const execDepth = 10;
const rootHash = transferTx.hash();
await enforcer.startWhitelisting(condProof, execDepth, rootHash, {value: bondAmount});

// const startTime = await time.latest();
// let exitTime = startTime + time.duration.seconds(exitDuration);
// await time.increaseTo(exitTime);

// await exitHandler.challengeExit(condProof, spendProof, 1, 1);

// const bal1 = await nativeToken.balanceOf(alice);

// exitTime = startTime + time.duration.seconds(exitDuration * 2);
// await time.increaseTo(exitTime);

// await exitHandler.finalizeTopExit(0);

// const bal2 = await nativeToken.balanceOf(alice);
// // check transfer didn't happen
// assert.equal(bal1.toNumber(), bal2.toNumber());
// // check exit was evicted from PriorityQueue
// assert.equal((await exitHandler.tokens(0))[1], 0);

// TODO: integrate with exitHandler.

});

});
2 changes: 1 addition & 1 deletion truffle-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module.exports = {
settings: {
optimizer: {
enabled: true,
runs: 200,
runs: 1,
},
// TODO: the code is supposed to work on constantinople EVM but fails if this is switched on
evmVersion: 'byzantium',
Expand Down
Loading