Skip to content

Commit

Permalink
refactor(core): generate network configuration with votes and transfers
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Faust committed Oct 24, 2019
1 parent eb52b94 commit 196be48
Show file tree
Hide file tree
Showing 23 changed files with 4,543 additions and 11,407 deletions.
3,788 changes: 1,384 additions & 2,404 deletions __tests__/unit/core-kernel/__stubs__/config-with-crypto/crypto/genesisBlock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions __tests__/unit/core-kernel/utils/assert.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { assert } from "@packages/core-kernel/src/utils/assert";
import { Blocks, Interfaces, Managers } from "@arkecosystem/crypto";
import { genesisBlock } from "@packages/core-test-framework/src/utils/fixtures/blocks";

Managers.configManager.setFromPreset("unitnet");

const block: Interfaces.IBlock = Blocks.BlockFactory.fromData(genesisBlock, { deserializeTransactionsUnchecked: true });
const block: Interfaces.IBlock = Blocks.BlockFactory.fromData(Managers.configManager.get("genesisBlock"), {
deserializeTransactionsUnchecked: true,
});

describe("Assertions", () => {
it(".defined", () => {
Expand Down
5 changes: 5 additions & 0 deletions __tests__/unit/core/commands/network/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ describe("GenerateCommand", () => {
"--token=myn",
"--symbol=my",
"--explorer=myex.io",
"--distribute",
]);

expect(existsSync).toHaveBeenCalledWith(configCore);
Expand Down Expand Up @@ -70,6 +71,7 @@ describe("GenerateCommand", () => {
"--token=myn",
"--symbol=my",
"--explorer=myex.io",
"--distribute",
]),
).rejects.toThrow(`${configCore} already exists.`);

Expand Down Expand Up @@ -97,6 +99,7 @@ describe("GenerateCommand", () => {
"--token=myn",
"--symbol=my",
"--explorer=myex.io",
"--distribute",
]),
).rejects.toThrow(`${configCrypto} already exists.`);

Expand Down Expand Up @@ -138,6 +141,7 @@ describe("GenerateCommand", () => {
"myn",
"my",
"myex.io",
true,
false,
]);

Expand Down Expand Up @@ -166,6 +170,7 @@ describe("GenerateCommand", () => {
"my",
"myex.io",
true,
true,
]);

await GenerateCommand.run([]);
Expand Down
8 changes: 5 additions & 3 deletions __tests__/unit/crypto/validation/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { TransactionTypeFactory } from "../../../../packages/crypto/src/transact
import { TransactionSchema } from "../../../../packages/crypto/src/transactions/types/schemas";
import { BigNumber } from "../../../../packages/crypto/src/utils";
import { validator } from "../../../../packages/crypto/src/validation";
import { block2, genesisBlock } from "../../../../packages/core-test-framework/src/utils/fixtures/blocks";
import { block2 } from "../../../../packages/core-test-framework/src/utils/fixtures/blocks";

describe("validator", () => {
describe("validate", () => {
Expand Down Expand Up @@ -259,8 +259,10 @@ describe("validator", () => {
});

it("should be ok", () => {
expect(validator.validate("block", block2).error).toBeUndefined();
expect(validator.validate("block", genesisBlock).error).toBeUndefined();
// note: those are outdated after the new unitnet config was generated
// expect(validator.validate("block", block2).error).toBeUndefined();
// expect(validator.validate("block", genesisBlock).error).toBeUndefined();
expect(validator.validate("block", configManager.get("genesisBlock")).error).toBeUndefined();
});

it("should not be ok", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core-kernel/src/services/events/drivers/memory.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { assert } from "@packages/core-kernel/src/utils";
import mm from "micromatch";

import { EventDispatcher as EventDispatcherContract } from "../../../contracts/kernel/events";
import { injectable } from "../../../ioc";
import { EventListener, EventName } from "../../../types/events";
import { assert } from "../../../utils";

/**
* @export
Expand Down
2 changes: 1 addition & 1 deletion packages/core-kernel/src/services/queue/drivers/memory.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { assert } from "@packages/core-kernel/src/utils";
import PQueue from "p-queue";

import { Queue } from "../../../contracts/kernel/queue";
import { injectable } from "../../../ioc";
import { assert } from "../../../utils";

/**
* @export
Expand Down
15 changes: 10 additions & 5 deletions packages/core-state/src/wallets/wallet-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class WalletState {
if (delegates.length < maxDelegates) {
throw new Error(
`Expected to find ${maxDelegates} delegates but only found ${delegates.length}. ` +
`This indicates an issue with the genesis block & delegates.`,
`This indicates an issue with the genesis block & delegates.`,
);
}

Expand All @@ -33,13 +33,18 @@ export class WalletState {
public buildVoteBalances(): void {
for (const voter of this.walletRepository.allByPublicKey()) {
if (voter.hasVoted()) {
const delegate: Contracts.State.Wallet = AppUtils.assert.defined(
this.walletRepository.findByPublicKey(voter.getAttribute<string>("vote")),
const delegate: Contracts.State.Wallet = this.walletRepository.findByPublicKey(
voter.getAttribute("vote"),
);

const voteBalance: Utils.BigNumber = delegate.getAttribute("delegate.voteBalance");
const lockedBalance = voter.getAttribute("htlc.lockedBalance");
delegate.setAttribute("delegate.voteBalance", voteBalance.plus(voter.balance).plus(lockedBalance));

if (voter.hasAttribute("htlc.lockedBalance")) {
delegate.setAttribute(
"delegate.voteBalance",
voteBalance.plus(voter.balance).plus(voter.getAttribute("htlc.lockedBalance")),
);
}
}
}
}
Expand Down
13 changes: 10 additions & 3 deletions packages/core-state/src/wallets/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class Wallet implements Contracts.State.Wallet {

private readonly attributes: Services.Attributes.AttributeMap;

public constructor (address: string) {
public constructor(address: string) {
this.address = address;
this.balance = Utils.BigNumber.ZERO;
this.nonce = Utils.BigNumber.ZERO;
Expand Down Expand Up @@ -70,9 +70,16 @@ export class Wallet implements Contracts.State.Wallet {
const attributes: object = this.attributes.all();

const hasAttributes: boolean = !!attributes && Object.keys(attributes).length > 0;
const lockedBalance = this.getAttribute("htlc.lockedBalance");

return this.balance.isZero() && lockedBalance.isZero() && !hasAttributes;
if (this.hasAttribute("htlc.lockedBalance")) {
const lockedBalance: AppUtils.BigNumber = this.getAttribute("htlc.lockedBalance");

if (!lockedBalance.isZero()) {
return false;
}
}

return this.balance.isZero() && !hasAttributes;
}

public applyBlock(block: Interfaces.IBlockData): boolean {
Expand Down
102 changes: 51 additions & 51 deletions packages/core-test-framework/src/utils/config/delegates.json
Original file line number Diff line number Diff line change
@@ -1,55 +1,55 @@
{
"secrets": [
"beach alert increase quit vessel address mandate click deny result play receive",
"girl smoke wrong keep fruit huge duck label buyer dizzy exhaust thrive",
"garage mix praise brush memory gallery drama credit fall afford powder still",
"genuine path nuclear spy arrange clip day this night journey gather pipe",
"below idea aim message advice hint shop chronic bright develop slow steel",
"lab change cancel inform throw today alter engine bamboo address core antenna",
"attract beauty license vacuum reunion various inmate multiply concert raven mimic hurry",
"early junior cargo sphere raise ethics collect spend funny beef anger awful",
"vital trade lyrics hedgehog peasant uncle coral veteran harbor stay know super",
"sign heavy tornado equip bag hobby reject seek voyage drill catch napkin",
"slam vintage pig design disagree tunnel crash sadness slogan tag use protect",
"trust theory sphere adapt under enhance valid leader sense equip arch inform",
"obvious bike worry flavor essay fault forward clutch lumber remind ring trap",
"diet castle oven kingdom much hunt cliff fine chunk tongue grant scrap",
"little shaft option steel depend knee file vendor cereal forum deal clever",
"quick fatigue split famous coral venture scale chronic urban hazard slow human",
"foot tag danger trash alone coyote report struggle motion such basic guilt",
"flock vendor hurry solid parent physical various hat wreck blouse pride script",
"humor dinosaur clever basic company march viable labor night sand mistake need",
"vacant session visual suggest supreme suspect surface birth scatter setup pipe catalog",
"napkin story fun asset cigar cage diesel spider cargo bless knee farm",
"section history result hold seat must dial awkward impose want pumpkin consider",
"worth atom wave inherit battle purpose rhythm crouch course agree solar shallow",
"tiger hammer space fox cereal harbor october divide solid secret retreat sad",
"device gap ladder time load shed clump rule taxi fury trophy observe",
"thumb answer owner always click parent glide exile peasant slim find risk",
"evidence museum beyond glimpse inner length story rent crater option liberty dignity",
"rural typical middle pluck service huge near fabric hurt base unaware trend",
"token rug empower easily hub resist clean early enlist purity avocado arch",
"skate pass help company speed chapter program fiber submit slam adult rescue",
"trophy plunge law minimum cause fitness derive cover bicycle truck help talk",
"spoil pink point speed mouse guide shield parent alcohol hurry toe glide",
"chat enrich draw release secret weather arctic language era total innocent finger",
"solution essence another ceiling diamond ship review swing emerge scrub version odor",
"addict enemy camp ship infant survey neutral kidney feature vacant hybrid double",
"tourist alter manual sausage scissors home illegal curious this hammer input ship",
"company cliff shiver grid false gallery zebra border record spring benefit time",
"moment found patient double have project service detail hard dilemma soup message",
"wool thought danger sniff profit concert fever fitness mosquito hour fox iron",
"equip cart desk public bonus boring useless what firm anxiety curtain twice",
"loop blouse media brief patch shell wage cat witness pioneer young solve",
"arrow autumn crew usage cluster dinosaur know buyer riot security fiscal door",
"eager erupt ensure fetch rebel submit avocado burger chicken tourist ensure transfer",
"slide violin dream hour old spare outside hospital use wear steak summer",
"annual endorse vessel impact company dinner trigger monitor way eight update picnic",
"alien giggle juice employ network miss interest kit candy apology hurt small",
"question private pill fan object duty wagon any jealous tail milk believe",
"impulse fly oyster wasp name view stadium army display bunker horn weird",
"step eager genius better differ divert hamster response soda key method shield",
"name gold lonely resource rude century fury time disease morning patch usual",
"cinnamon skin option float carpet great clinic gorilla leader erode arrange tourist"
"clay harbor enemy utility margin pretty hub comic piece aerobic umbrella acquire",
"venue below waste gather spin cruise title still boost mother flash tuna",
"craft imitate step mixture patch forest volcano business charge around girl confirm",
"fatal hat sail asset chase barrel pluck bag approve coral slab bright",
"flash thank strike stove grain remove match reflect excess present beyond matrix",
"various present shine domain outdoor neck soup diesel limit express genuine tuna",
"hurdle pulse sheriff anchor two hope income pattern hazard bacon book night",
"glow boss party require silk interest pyramid marriage try wisdom snow grab",
"direct palace screen shuffle world fit produce rubber jelly gather river ordinary",
"wall ketchup shed word twist flip knock liar merge rural ill pond",
"measure blue volcano month orphan only cupboard found laugh peasant drama monitor",
"scissors sort pause medal target diesel reveal stock maze party gauge vacant",
"hand anchor hip pyramid taxi vote celery clap tribe damage shrimp brave",
"merge thunder detect stove else bottom favorite doll learn festival basic basic",
"educate attitude rely combine treat balcony west reopen coil west grab depth",
"advance silver advance squeeze load stone middle garden perfect invest field lounge",
"prison tobacco acquire stone dignity palace note decade they current lesson robot",
"team impact stadium year security steak harsh vacant fire pelican until olympic",
"walk intact ice prevent fit trial frog glory monkey once grunt gentle",
"same lens parrot suspect just sunset frown exercise lemon two mistake robust",
"skill insect issue crazy erase okay govern upgrade bounce dress motor athlete",
"peasant alert hard deposit naive follow page fiscal normal awful wedding history",
"resemble abandon same total oppose noise dune order fatal rhythm pink science",
"wide mesh ketchup acquire bright day mountain final below hamster scout drive",
"half weasel poet better rocket fan help left blade soda argue system",
"target sort neutral address language spike measure jaguar glance strong drop zone",
"race total stage trap wool believe twin pudding claim claim eternal miss",
"parade isolate wing vague magic husband acid skin skate path fence rib",
"neither fine dry priority example obtain bread reopen afford coyote milk minor",
"token atom lemon game charge area goose hotel excess endless spice oblige",
"pledge buffalo finish pipe mule popular bind clinic draft salon swamp purpose",
"west hat hold stand unique panther cable extend spell shaft injury reopen",
"van impulse pole install profit excuse give auction expire remain skate input",
"wrist maze potato april survey burden bamboo knee foot carry speak prison",
"three toddler copy owner pencil minimum doctor orange bottom ice detail design",
"ceiling warrior person thing whisper jeans black cricket drift ahead tornado typical",
"obvious mutual tone usual valve credit soccer mention also clown main box",
"valve slot soft green scale menu anxiety live drill legend upgrade chimney",
"twist comfort mule weather print oven cabin seek punch rival prepare sphere",
"say tumble glass argue aware service force caution until grocery hammer fetch",
"idea illegal empty frozen canvas arctic number poet rely track size obscure",
"chalk try large tower shed warfare blade clerk fame second charge tobacco",
"category nice verb fox start able brass climb boss luggage voice whale",
"favorite emotion trumpet visual welcome spend fine lock image review garage opera",
"waste axis humor auction next salmon much margin useful glimpse insect rotate",
"remember rose genuine police guard old flavor parent gain cross twelve first",
"coil tray elder mask circle crush anger electric harbor onion grab will",
"shove airport bus gather radio derive below horse canvas crime tribe adjust",
"retire lend burden cricket able sheriff output grocery empty scorpion flat inquiry",
"agree grain record shift fossil summer hunt mutual net vast behind pilot",
"decide rhythm oyster lady they merry betray jelly coyote solve episode then"
]
}
Loading

0 comments on commit 196be48

Please sign in to comment.