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

feat: add previous period hash to proofs and roots if present #166

Merged
merged 4 commits into from
Dec 23, 2019
Merged
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
19 changes: 14 additions & 5 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,15 +254,24 @@ declare module "leap-core" {
public static from(height: number, timestamp: number, txList: LeapTransaction[]): Block;
}

type PeriodOptions = {
validatorData?: {
slotId: number;
ownerAddr: string | Buffer | number;
casBitmap?: string | Buffer | number;
};
excludePrevHashFromProof?: Boolean;
};

class Period {
constructor(prevHash: string, blocks: Array<Block>);
constructor(prevHash: string, blocks: Array<Block>, opts?: PeriodOptions);
addBlock(block: Block): Period;
getMerkleTree(): MerkleTree;
merkleRoot(): string;
proof(tx: Tx<any>): Proof;
static periodBlockRange(blockNumber: number): [number, number];
static periodForBlockRange(plasma: ExtendedWeb3, startBlock: number, endBlock: number): Promise<Period>;
static periodForTx(plasma: ExtendedWeb3, tx: LeapTransaction): Promise<Period>;
static periodForBlockRange(plasma: ExtendedWeb3, startBlock: number, endBlock: number, periodOpts?: PeriodOptions): Promise<Period>;
static periodForTx(plasma: ExtendedWeb3, tx: LeapTransaction, periodOpts?: PeriodOptions): Promise<Period>;
}

export type Proof = string[];
Expand Down Expand Up @@ -331,7 +340,7 @@ declare module "leap-core" {
};

type PeriodData = {
validatorAddress: string;
ownerAddr: string;
slotId: number;
casBitmap?: string;
periodStart?: number;
Expand Down Expand Up @@ -360,7 +369,7 @@ declare module "leap-core" {
export function periodBlockRange(blockNumber: number): [number, number];
export function getTxWithYoungestBlock(txs: LeapTransaction[]): InputTx;
export function getYoungestInputTx(plasma: ExtendedWeb3, tx: Tx<any>): Promise<InputTx>;
export function getProof(plasma: ExtendedWeb3, tx: LeapTransaction, fallbackPeriodData?: PeriodData): Promise<Proof>;
export function getProof(plasma: ExtendedWeb3, tx: LeapTransaction, periodOpts?: PeriodOptions): Promise<Proof>;
// Depending on plasma instance, resolves to either Web3's Transaction or Ethers' TransactionReceipt
export function sendSignedTransaction(plasma: ExtendedWeb3, tx: string): Promise<any>;
export function simulateSpendCond(plasma: ExtendedWeb3, tx: Tx<Type.SPEND_COND>): Promise<SpendCondSimResult>;
Expand Down
23 changes: 12 additions & 11 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,25 +213,26 @@ export function getYoungestInputTx(plasma, tx) {
*
* @param {ExtendedWeb3|LeapProvider} plasma instance of Leap Web3
* @param {LeapTransaction} tx
* @param {PeriodOpts} periodOpts — options for cosntructed Period as defined in Period constructor
* @returns {Promise<Proof>} promise that resolves to period inclusion proof
*/
export function getProof(plasma, tx, fallbackPeriodData) {
return Promise.all([
Period.periodForTx(plasma, tx),
plasma.getPeriodByBlockHeight(tx.blockNumber)
]).then(([period, periodData]) => {
const [periodDataObj] = periodData || [fallbackPeriodData];
if (!periodData || !periodData.length) {
export function getProof(plasma, tx, periodOpts = {}) {
return plasma.getPeriodByBlockHeight(tx.blockNumber)
.then(periodData => {
if (periodData && periodData.length) {
Object.assign(periodOpts, {
validatorData: periodData[0],
});
} else {
const msg = `No period data for the given tx. Height: ${tx.blockNumber}`;
if (!fallbackPeriodData) {
if (!periodOpts.validatorData) {
throw new Error(msg);
} else {
console.warn(msg, 'Using fallback values'); // eslint-disable-line no-console
}
}
const { slotId, validatorAddress, casBitmap } = periodDataObj;

period.setValidatorData(slotId, validatorAddress, casBitmap);
return Period.periodForTx(plasma, tx, periodOpts);
}).then((period) => {
return period.proof(Tx.fromRaw(tx.raw));
});
}
Expand Down
19 changes: 13 additions & 6 deletions lib/helpers.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ describe('helpers', () => {
const transactions = n === 4 ? [{ raw: deposit1.hex() }] : [];
return { number: n, timestamp: 123, transactions };
},
getPeriodByBlockHeight: () => null,
getPeriodByBlockHeight: () => Promise.resolve(null),
};

expect(
Expand All @@ -199,15 +199,18 @@ describe('helpers', () => {
const transactions = n === 4 ? [{ raw: deposit1.hex() }] : [];
return { number: n, timestamp: 123, transactions };
},
getPeriodByBlockHeight: () => null,
getPeriodByBlockHeight: () => Promise.resolve(null),
};

const fallbackData = { slotId: 0, validatorAddress: ADDR_1 };
const periodOpts = {
validatorData: { slotId: 0, ownerAddr: ADDR_1 },
excludePrevHashFromProof: true,
};

const proof = getProof(
plasma,
{ blockNumber: 4, raw: deposit1.hex() },
fallbackData
periodOpts
);
return expect(proof).to.eventually.eql([
'0x29aa1b0213471dbf84175e8f688e5a63c2e5724ad6bc581a10b9521f4b8a6083',
Expand Down Expand Up @@ -240,11 +243,15 @@ describe('helpers', () => {
},
getPeriodByBlockHeight: n => {
expect(n).to.be.equal(4);
return [{ slotId: 0, validatorAddress: ADDR_1, casBitmap }];
return Promise.resolve([{ slotId: 0, ownerAddr: ADDR_1, casBitmap }]);
},
};

const proof = getProof(plasma, { blockNumber: 4, raw: deposit1.hex() });
const proof = getProof(
plasma,
{ blockNumber: 4, raw: deposit1.hex() },
{ excludePrevHashFromProof: true }
);
return expect(proof).to.eventually.eql([
'0x6eefe22ae29bc837d66e743334a70ecc19635c3c9ef31d4c2987b337b9d015c6',
'0x4404003c00000000000000080000000000000000000000000000000000000000',
Expand Down
106 changes: 98 additions & 8 deletions lib/period.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,40 @@ import Util from './util';
import { BLOCKS_PER_PERIOD } from './constants';

export default class Period {
constructor(prevHash, blocks) {

/**
*
* Create a Period object linked to the previous Period via `prevHash` and
* containing given list of `blocks`.
*
* Optional parameters can be given via `opts` argument. Format as follows:
*
* type PeriodOptions = {
* validatorData?: {
* slotId: number;
* ownerAddr: string | Buffer | number;
* casBitmap?: string | Buffer | number;
* };
* excludePrevHashFromProof?: Boolean;
* };
*
* @param {string} prevHash - previous period root hash
* @param {Array<Block>} blocks - array of blocks to include in the period
* @param {PeriodOptions} opts - options defined as above. Default {}
*/
constructor(prevHash, blocks, opts = {}) {
this.prevHash = prevHash;
this.blockList = [];
this.blockHashList = [];
this.usePrev = !opts.excludePrevHashFromProof;
if (blocks) {
blocks.forEach(block => this.addBlock(block));
}

const { slotId, ownerAddr, casBitmap } = opts.validatorData || {};
if ((slotId || slotId === 0) && ownerAddr) {
this.setValidatorData(slotId, ownerAddr, casBitmap);
}
}

addBlock(block) {
Expand Down Expand Up @@ -64,6 +91,19 @@ export default class Period {
}
}

//
/**
* helpful: https://docs.google.com/drawings/d/13oFjua-v_E_yaFYUbralluI-EysgtTaZb_sSgGbxG_A
*
* period root
* / \
* consensus root CAS root
* / \ / \
* blocks root meta root CAS bitmap validator root
* / \ / \
* fees hash prevPeriodHash * slotId 0x0
* * ownerAddr
*/
periodData() {
if (typeof this.slotId === 'undefined' || !this.ownerAddr) {
throw Error('period is missing validator data to create period root.');
Expand All @@ -81,11 +121,20 @@ export default class Period {
}
validatorRoot.copy(rootBuf, 32);
const casRoot = keccak256(rootBuf);


// make metaRoot
let metaRoot = Buffer.alloc(32, 0);
if (this.usePrev) {
rootBuf = Buffer.alloc(64, 0);
toBuffer(this.prevHash).copy(rootBuf, 32);
metaRoot = keccak256(rootBuf);
}

// make consensusRoot
const blocksRoot = this.getMerkleTree().getRoot();
rootBuf = Buffer.alloc(64, 0);
blocksRoot.copy(rootBuf);
metaRoot.copy(rootBuf, 32);
const consensusRoot = keccak256(rootBuf);

// make period root
Expand All @@ -96,6 +145,7 @@ export default class Period {
return {
casRoot,
periodRoot,
metaRoot
};
}

Expand All @@ -104,6 +154,44 @@ export default class Period {
return periodRoot;
}

prevPeriodProof() {
if (!this.usePrev) {
throw Error('not set to use prev period in proofs');
}

const { casRoot } = this.periodData();

const proof = [];

// fees hash
proof.push(bufferToHex(Buffer.alloc(32, 0)));
proof.push(this.prevHash);
proof.push(this.merkleRoot());
proof.push(bufferToHex(casRoot));

return proof;
}

// returns [currentPeriodRoot, prevPeriodRoot]
static evaluatePrevPeriodProof(proof) {
let result;
result = Buffer.alloc(64, 0);
// fees hash
toBuffer(proof[0]).copy(result);
// prevPeriod
toBuffer(proof[1]).copy(result, 32);
const metaRoot = keccak256(result);
result = Buffer.alloc(64, 0);
// blocks root
toBuffer(proof[2]).copy(result);
metaRoot.copy(result, 32);
const consensusRoot = keccak256(result);
result = Buffer.alloc(64, 0);
toBuffer(consensusRoot).copy(result);
toBuffer(proof[3]).copy(result, 32);
return [proof[1], bufferToHex(keccak256(result))];
}

proof(tx) {
let periodPos = -1;
for (let i = 0; i < this.blockList.length; i++) {
Expand All @@ -130,10 +218,10 @@ export default class Period {
blockProof.forEach(elem => proof.push(elem));

// add extensible proof structure
const { casRoot, periodRoot } = this.periodData();
const { casRoot, periodRoot, metaRoot } = this.periodData();

// update the proof
proof.push(bufferToHex(Buffer.alloc(32, 0)));
proof.push(bufferToHex(metaRoot));
proof.push(bufferToHex(casRoot));
proof[0] = periodRoot;
return proof;
Expand All @@ -159,9 +247,10 @@ export default class Period {
* @param {ExtendedWeb3} plasma instance of Leap Web3 or Leap Ethers
* @param {Number} startBlock first block to include in the period
* @param {Number} endBlock last block to include in the period
* @param {PeriodOpts} periodOpts options for Period object as defined in Period constructor
* @returns {Period} period
*/
static periodForBlockRange(plasma, startBlock, endBlock) {
static periodForBlockRange(plasma, startBlock, endBlock, periodOpts = {}) {
return Promise.all(
Util.range(startBlock, endBlock).map(n => (plasma.eth || plasma).getBlock(n, true)),
).then((blocks) => {
Expand All @@ -170,7 +259,7 @@ export default class Period {
.map(({ number, timestamp, transactions }) =>
Block.from(number, timestamp, transactions),
);
return new Period(null, blockList);
return new Period(null, blockList, periodOpts);
});
}

Expand All @@ -179,12 +268,13 @@ export default class Period {
*
* @param {ExtendedWeb3} plasma instance of Leap Web3
* @param {Transaction} tx transaction to create {Period} for
* @param {PeriodOpts} periodOpts options for Period object as defined in Period constructor
* @returns {Period} period
*/
static periodForTx(plasma, tx) {
static periodForTx(plasma, tx, periodOpts = {}) {
const { blockNumber } = tx;
const [startBlock, endBlock] = Period.periodBlockRange(blockNumber);
return Period.periodForBlockRange(plasma, startBlock, endBlock);
return Period.periodForBlockRange(plasma, startBlock, endBlock, periodOpts);
}

}
Loading