Skip to content

Commit

Permalink
Merge branch 'nft' into deniallugo-nft-backward-compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
Deniallugo authored May 28, 2021
2 parents 897be04 + ba44e99 commit 9e25dcb
Show file tree
Hide file tree
Showing 45 changed files with 692 additions and 443 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ This architecture provides the following guarantees:

In other words, ZK Rollup strictly inherits the security guarantees of the underlying L1.

To learn how to use zkSync, please refer to the [zkSync SDK documentation](https://zksync.io).
To learn how to use zkSync, please refer to the [zkSync SDK documentation](https://zksync.io/api/sdk/).

## Development Documentation

Expand Down
28 changes: 22 additions & 6 deletions contracts/contracts/Operations.sol
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ library Operations {
/// @dev Signature (for example full exit signature) bytes length
uint8 internal constant SIGNATURE_BYTES = 64;

uint256 internal constant LEGACY_MAX_TOKEN = 65535; // 2^16 - 1

// Deposit pubdata
struct Deposit {
// uint8 opType
Expand Down Expand Up @@ -94,9 +96,16 @@ library Operations {

/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return
Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata ||
Utils.hashBytesToBytes20(writeLegacyDepositPubdataForPriorityQueue(op)) == hashedPubdata;
if (Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata) {
return true;
} else if (
op.tokenId <= LEGACY_MAX_TOKEN &&
Utils.hashBytesToBytes20(writeLegacyDepositPubdataForPriorityQueue(op)) == hashedPubdata
) {
return true;
} else {
return false;
}
}

// FullExit pubdata
Expand Down Expand Up @@ -164,9 +173,16 @@ library Operations {
}

function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return
Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata ||
Utils.hashBytesToBytes20(writeLegacyFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
if (Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata) {
return true;
} else if (
op.tokenId <= LEGACY_MAX_TOKEN &&
Utils.hashBytesToBytes20(writeLegacyFullExitPubdataForPriorityQueue(op)) == hashedPubdata
) {
return true;
} else {
return false;
}
}

// PartialExit pubdata
Expand Down
22 changes: 12 additions & 10 deletions contracts/scripts/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@ async function main() {
return;
}
const addresses = deployedAddressesFromEnv();
for (const address of [
addresses.ZkSyncTarget,
addresses.VerifierTarget,
addresses.GovernanceTarget,
addresses.UpgradeGatekeeper
]) {
for (const address of [addresses.ZkSyncTarget, addresses.VerifierTarget, addresses.GovernanceTarget]) {
try {
await hre.run('verify', { address });
await hre.run('verify:verify', { address });
} catch (e) {
console.error(e);
}
}

{
const address = addresses.UpgradeGatekeeper;
const constructorArguments = [addresses.ZkSync];

await hre.run('verify:verify', { address, constructorArguments });
}

{
const address = addresses.ZkSync;
const zkSyncEncodedArguments = ethers.utils.defaultAbiCoder.encode(
Expand All @@ -32,7 +34,7 @@ async function main() {
const constructorArguments = [addresses.ZkSyncTarget, zkSyncEncodedArguments];

try {
await hre.run('verify', { address, constructorArguments });
await hre.run('verify:verify', { address, constructorArguments });
} catch (e) {
console.error(e);
}
Expand All @@ -45,7 +47,7 @@ async function main() {
const constructorArguments = [addresses.GovernanceTarget, governanceEncodedArguments];

try {
await hre.run('verify', { address, constructorArguments });
await hre.run('verify:verify', { address, constructorArguments });
} catch (e) {
console.error(e);
}
Expand All @@ -58,7 +60,7 @@ async function main() {
const constructorArguments = [addresses.VerifierTarget, verifierEncodedArguments];

try {
await hre.run('verify', { address, constructorArguments });
await hre.run('verify:verify', { address, constructorArguments });
} catch (e) {
console.error(e);
}
Expand Down
104 changes: 78 additions & 26 deletions contracts/scripts/submit-regenesis-upgrade.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ArgumentParser } from 'argparse';
import { deployContract } from 'ethereum-waffle';
import { constants, ethers } from 'ethers';
import { Contract, ethers } from 'ethers';
import * as fs from 'fs';
import * as path from 'path';
import { web3Provider, storedBlockInfoParam } from './utils';
Expand All @@ -10,6 +10,60 @@ const testConfigPath = path.join(process.env.ZKSYNC_HOME as string, `etc/test_co
const ethTestConfig = JSON.parse(fs.readFileSync(`${testConfigPath}/eth.json`, { encoding: 'utf-8' }));
const testContracts = readProductionContracts();

async function startUpgrade(wallet: ethers.Wallet, upgradeGatekeeper: Contract) {
console.log('Deploying new Governance target...');
const newTargetGov = await deployContract(wallet, testContracts.governance, [], {
gasLimit: 6500000
});

console.log('Deploying new Verifier target...');
const newTargetVerifier = await deployContract(wallet, testContracts.verifier, [], {
gasLimit: 6500000
});

console.log('Deploying new zkSync target...');
const newTargetZkSync = await deployContract(wallet, testContracts.zkSync, [], {
gasLimit: 6500000
});

console.log('Starting upgrade...');
await (
await upgradeGatekeeper.startUpgrade(
[newTargetGov.address, newTargetVerifier.address, newTargetZkSync.address],
{
gasLimit: 500000
}
)
).wait();
console.log('Upgrade has been successfully started.');
}

async function startPreparation(upgradeGatekeeper: Contract) {
console.log('Trying to start preparation...');
while (parseInt(await upgradeGatekeeper.upgradeStatus()) !== 2 /*Preparation*/) {
await new Promise((r) => setTimeout(r, 1000));
await (await upgradeGatekeeper.startPreparation({ gasLimit: 300000 })).wait();
}
console.log('Upgrade preparation has been successfully started');
}

async function finishUpgrade(upgradeGatekeeper: Contract, lastBlockInfo: string) {
const blockInfo = JSON.parse(lastBlockInfo);
const upgradeData = ethers.utils.defaultAbiCoder.encode([storedBlockInfoParam()], [blockInfo]);

console.log('Finishing upgrade');
await (await upgradeGatekeeper.finishUpgrade([[], [], upgradeData], { gasLimit: 3000000 })).wait();
console.log('The upgrade has finished');
}

async function cancelUpgrade(upgradeGatekeeper: Contract) {
await (
await upgradeGatekeeper.cancelUpgrade({
gasLimit: 500000
})
).wait();
}

async function main() {
const parser = new ArgumentParser({
version: '0.0.1',
Expand All @@ -19,10 +73,12 @@ async function main() {
parser.addArgument('--masterPrivateKey');
parser.addArgument('--upgradeGatekeeperAddress');
parser.addArgument('--lastBlockInfo');
parser.addArgument('--startUpgrade');
parser.addArgument('--finishUpgrade');
parser.addArgument('--startPreparation');
parser.addArgument('--cancelUpgrade');
const args = parser.parseArgs(process.argv.slice(2));

const lastBlockInfo = JSON.parse(args.lastBlockInfo);

const provider = web3Provider();
const wallet = args.masterPrivateKey
? new ethers.Wallet(args.masterPrivateKey).connect(provider)
Expand All @@ -34,34 +90,30 @@ async function main() {
wallet
);

const newTargetZkSync = await deployContract(wallet, testContracts.zkSync, [], {
gasLimit: 6500000
});

const newTargetGov = await deployContract(wallet, testContracts.governance, [], {
gasLimit: 6500000
});
if (!args.startUpgrade && !args.startPreparation && !args.finishUpgrade && !args.cancelUpgrade) {
console.log(`Please supply at least one of the following flags:
--startUpgrade,
--startPreparation,
--finishUpgrade
`);
return;
}

const upgradeData = ethers.utils.defaultAbiCoder.encode([storedBlockInfoParam()], [lastBlockInfo]);
if (args.startUpgrade) {
await startUpgrade(wallet, upgradeGatekeeper);
}

console.log('Starting upgrade');
await (
await upgradeGatekeeper.startUpgrade([newTargetGov.address, constants.AddressZero, newTargetZkSync.address], {
gasLimit: 500000
})
).wait();
if (args.startPreparation) {
await startPreparation(upgradeGatekeeper);
}

// wait notice period
console.log('Waiting notice period');
while (parseInt(await upgradeGatekeeper.upgradeStatus()) !== 2 /*Preparation*/) {
await new Promise((r) => setTimeout(r, 1000));
await (await upgradeGatekeeper.startPreparation({ gasLimit: 300000 })).wait();
if (args.finishUpgrade) {
await finishUpgrade(upgradeGatekeeper, args.lastBlockInfo);
}

console.log('Finish upgrade notice period');
// console.log(await proxyContract.exodusMode());
// finish upgrade
await (await upgradeGatekeeper.finishUpgrade([[], [], upgradeData], { gasLimit: 3000000 })).wait();
if (args.cancelUpgrade) {
await cancelUpgrade(upgradeGatekeeper);
}
}

main()
Expand Down
4 changes: 3 additions & 1 deletion contracts/src.ts/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export interface DeployedAddresses {
ForcedExit: string;
RegenesisMultisig: string;
NFTFactory: string;
AdditionalZkSync: string;
}

export interface DeployerConfig {
Expand Down Expand Up @@ -87,7 +88,8 @@ export function deployedAddressesFromEnv(): DeployedAddresses {
ZkSync: process.env.CONTRACTS_CONTRACT_ADDR,
ZkSyncTarget: process.env.CONTRACTS_CONTRACT_TARGET_ADDR,
ForcedExit: process.env.CONTRACTS_FORCED_EXIT_ADDR,
RegenesisMultisig: process.env.MISC_REGENESIS_MULTISIG_ADDRESS
RegenesisMultisig: process.env.MISC_REGENESIS_MULTISIG_ADDRESS,
AdditionalZkSync: process.env.MISC_NEW_ADDITIONAL_ZKSYNC_ADDRESS
};
}

Expand Down
1 change: 1 addition & 0 deletions core/bin/data_restore/src/contract/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub fn rollup_ops_blocks_from_bytes(input_data: Vec<u8>) -> Result<RollupOpsBloc
fee_account,
timestamp: None,
previous_block_root_hash: H256::default(),
contract_version: None,
};
Ok(block)
} else {
Expand Down
1 change: 1 addition & 0 deletions core/bin/data_restore/src/contract/v4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub fn rollup_ops_blocks_from_bytes(data: Vec<u8>) -> anyhow::Result<Vec<RollupO
fee_account: AccountId(fee_acc.as_u32()),
timestamp: Some(timestamp.as_u64()),
previous_block_root_hash,
contract_version: None,
});

previous_block_root_hash = H256::from_slice(&root_hash);
Expand Down
33 changes: 31 additions & 2 deletions core/bin/data_restore/src/contract/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,39 @@ impl ZkSyncContractVersion {
data: Vec<u8>,
) -> anyhow::Result<Vec<RollupOpsBlock>> {
use ZkSyncContractVersion::*;
let res = match self {
let mut blocks = match self {
V0 | V1 | V2 | V3 => vec![contract::default::rollup_ops_blocks_from_bytes(data)?],
V4 => contract::v4::rollup_ops_blocks_from_bytes(data)?,
};
Ok(res)
// Set the contract version.
for block in blocks.iter_mut() {
block.contract_version = Some(*self);
}
Ok(blocks)
}

/// Returns the contract version incremented by `num`.
///
/// # Arguments
///
/// * `num` - how many times to upgrade.
///
/// # Panics
///
/// Panics if the the result is greater than the latest supported version.
pub fn upgrade(&self, num: u32) -> Self {
Self::try_from(i32::from(*self) as u32 + num)
.expect("cannot upgrade past the latest contract version")
}

/// Returns supported block chunks sizes by the verifier contract
/// with the given version.
pub fn available_block_chunk_sizes(&self) -> &'static [usize] {
use ZkSyncContractVersion::*;
match self {
V0 | V1 | V2 => &[6, 30, 74, 150, 334, 678],
V3 => &[6, 30, 74, 150, 320, 630],
V4 => &[10, 32, 72, 156, 322, 654],
}
}
}
Loading

0 comments on commit 9e25dcb

Please sign in to comment.