diff --git a/ci/contracts/executor_harness.py b/ci/contracts/executor_harness.py new file mode 100644 index 000000000..1e51f05b8 --- /dev/null +++ b/ci/contracts/executor_harness.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +"""Run token smart contracts on a contract executor without a node, and compare executors. + +Usage: executor_harness.py --jar contract-executor.jar [--jar other.jar ...] --jdk JDK_DIR + [--work DIR] [--json OUT] [--only NAME,...] [--java-opt OPT ...] + +For every jar the harness starts the executor with a settings.properties of its own and a stub of +the node's APIEXEC service (GetSeed, SmartContractGet, WalletBalanceGet, GetDateTime: fixed, +deterministic answers), then runs the scenarios in token_scenarios.py through the executor's +Thrift interface the way the node does: deploy (executeByteCode with an empty state), calls +(executeByteCode with the last state), getters (executeByteCodeMultiple, state not kept) and +getContractMethods (the token standard the API records). + +Each step records the status code, the return value, a hash of every contract state the executor +returns and the emitted transactions. The first jar is the reference (the release executor): with +two or more jars, any step whose record differs is a FAIL, because the node accepts a contract +result only if the confidants' executors agree. Every scenario also checks its own expectations +(an expectation that does not hold is reported as a finding, not as a difference). +""" +import argparse +import hashlib +import json +import os +import socket +import subprocess +import sys +import threading +import time + +import base58 +import thriftpy2 +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.rpc import make_client, make_server +from thriftpy2.transport import TBufferedTransportFactory + +HERE = os.path.dirname(os.path.abspath(__file__)) +IDL = os.path.abspath(os.path.join(HERE, "..", "..", "third-party", "thrift-interface-definitions")) +general = thriftpy2.load(os.path.join(IDL, "general.thrift"), module_name="general_thrift", include_dirs=[IDL]) +api = thriftpy2.load(os.path.join(IDL, "api.thrift"), module_name="api_thrift", include_dirs=[IDL]) +executor = thriftpy2.load(os.path.join(IDL, "executor.thrift"), module_name="executor_thrift", include_dirs=[IDL]) +apiexec = thriftpy2.load(os.path.join(IDL, "apiexec.thrift"), module_name="apiexec_thrift", include_dirs=[IDL]) + +EXECUTOR_VERSION = 4 # cs::Executor::EXECUTOR_VERSION +EXECUTION_TIME = 10000 # ms; the node uses Consensus::TimeSmartContract (2 s), a cold JVM needs more +BLOCK_TIME_MS = 1_700_000_000_000 + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def key(name): + """A deterministic 32-byte address for a test actor.""" + return hashlib.sha256(name.encode()).digest() + + +def b58(addr): + return base58.b58encode(addr).decode() + + +# --------------------------------------------------------------------------------------------- +# Variant helpers +# --------------------------------------------------------------------------------------------- +def v_str(s): + return general.Variant(v_string=s) + + +def v_dec(s): + return general.Variant(v_big_decimal=str(s)) + + +def v_bytes(b): + return general.Variant(v_byte_array=b) + + +def v_bool(b): + return general.Variant(v_boolean=b) + + +def v_int(i): + return general.Variant(v_int=i) + + +def variant_value(v): + """A plain, JSON friendly value of a Variant (None for an unset one).""" + if v is None: + return None + for name in ("v_null", "v_void", "v_boolean", "v_boolean_box", "v_byte", "v_byte_box", "v_short", + "v_short_box", "v_int", "v_int_box", "v_long", "v_long_box", "v_float", "v_float_box", + "v_double", "v_double_box", "v_string", "v_big_decimal"): + value = getattr(v, name, None) + if value is not None: + return {name: value} + if v.v_byte_array is not None: + return {"v_byte_array": v.v_byte_array.hex()} + if v.v_amount is not None: + return {"v_amount": [v.v_amount.integral, v.v_amount.fraction]} + for name in ("v_array", "v_list"): + value = getattr(v, name, None) + if value is not None: + return {name: [variant_value(x) for x in value]} + if v.v_map is not None: + return {"v_map": sorted([json.dumps(variant_value(k)), json.dumps(variant_value(x))] for k, x in v.v_map.items())} + if v.v_object is not None: + return {"v_object": v.v_object.nameClass} + return {} + + +def plain(v): + """The bare value of a Variant: a string, a number or a bool.""" + value = variant_value(v) or {} + return next(iter(value.values()), None) + + +def first_line(message, limit=300): + message = (message or "").strip() + # the executor sends the root cause stack trace; its first line is the exception + return message.splitlines()[0][:limit] if message else "" + + +# --------------------------------------------------------------------------------------------- +# Stub of the node's APIEXEC service +# --------------------------------------------------------------------------------------------- +class NodeStub: + """What a contract can ask the node: answers are fixed, so every executor sees the same.""" + + def __init__(self): + self.contracts = {} # address -> (byteCodeObjects, state) + self.balances = {} # address -> (integral, fraction) + self.calls = [] + + def GetSeed(self, accessId): + self.calls.append("GetSeed") + return apiexec.GetSeedResult(status=general.APIResponse(code=0, message=""), + seed=hashlib.sha256(b"seed%d" % accessId).digest()) + + def SendTransaction(self, accessId, transaction): + self.calls.append("SendTransaction") + return apiexec.SendTransactionResult(status=general.APIResponse(code=0, message="")) + + def SmartContractGet(self, accessId, address): + self.calls.append("SmartContractGet " + b58(address)) + if address not in self.contracts: + return apiexec.SmartContractGetResult(status=general.APIResponse(code=1, message="no contract"), + byteCodeObjects=[], contractState=b"", stateCanModify=False) + bco, state = self.contracts[address] + return apiexec.SmartContractGetResult(status=general.APIResponse(code=0, message=""), + byteCodeObjects=bco, contractState=state, stateCanModify=True) + + def WalletIdGet(self, accessId, address): + self.calls.append("WalletIdGet") + return api.WalletIdGetResult(status=general.APIResponse(code=0, message=""), walletId=1) + + def WalletBalanceGet(self, address): + self.calls.append("WalletBalanceGet") + integral, fraction = self.balances.get(address, (0, 0)) + return api.WalletBalanceGetResult(status=general.APIResponse(code=0, message=""), + balance=general.Amount(integral=integral, fraction=fraction)) + + def PoolGet(self, sequence): + return apiexec.PoolGetResult(status=general.APIResponse(code=1, message="not in the stub"), pool=b"") + + def GetDateTime(self, accessId): + self.calls.append("GetDateTime") + return apiexec.GetDateTimeResult(status=general.APIResponse(code=0, message=""), timestamp=BLOCK_TIME_MS) + + +# --------------------------------------------------------------------------------------------- +# One executor process +# --------------------------------------------------------------------------------------------- +class Executor: + def __init__(self, jar, jdk, work, java_opts=()): + self.java_opts = list(java_opts) + self.jar = os.path.abspath(jar) + self.jdk = os.path.abspath(jdk) + self.work = work + self.stub = NodeStub() + self.node_port = free_port() + self.port = free_port() + self.proc = None + self.server = None + self.access_id = 1000 + + def start(self): + os.makedirs(self.work, exist_ok=True) + with open(os.path.join(self.work, "settings.properties"), "w") as f: + f.write(f"node.api.host=127.0.0.1\nnode.api.port=1\ncontract.executor.port={self.port}\n" + f"contract.executor.node.api.port={self.node_port}\ncontract.executor.node.api.host=127.0.0.1\n" + f"contract.executor.read.client.timeout=0\njdk.path={self.jdk}\n") + self.server = make_server(apiexec.APIEXEC, self.stub, "127.0.0.1", self.node_port, + proto_factory=TBinaryProtocolFactory(), trans_factory=TBufferedTransportFactory()) + threading.Thread(target=self.server.serve, daemon=True).start() + self.log = open(os.path.join(self.work, "executor.log"), "w") + self.proc = subprocess.Popen([os.path.join(self.jdk, "bin", "java"), "-Xmx512m", *self.java_opts, "-jar", self.jar], + cwd=self.work, stdout=self.log, stderr=subprocess.STDOUT) + deadline = time.time() + 90 + while time.time() < deadline: + if self.proc.poll() is not None: + raise RuntimeError(f"executor {self.jar} exited, see {self.work}/executor.log") + try: + c = self.client() + c.getExecutorBuildVersion(EXECUTOR_VERSION) + c.close() + return + except Exception: + time.sleep(1) + raise RuntimeError(f"executor {self.jar} did not answer in 90 s") + + def client(self, timeout=120000): + return make_client(executor.ContractExecutor, "127.0.0.1", self.port, proto_factory=TBinaryProtocolFactory(), + trans_factory=TBufferedTransportFactory(), timeout=timeout) + + def stop(self): + if self.proc and self.proc.poll() is None: + self.proc.terminate() + try: + self.proc.wait(10) + except subprocess.TimeoutExpired: + self.proc.kill() + if self.server: + try: + self.server.close() + except Exception: + pass + + def restart(self): + self.stop() + self.stub = NodeStub() + self.node_port = free_port() + self.port = free_port() + self.start() + + def next_access_id(self): + self.access_id += 1 + return self.access_id + + +# --------------------------------------------------------------------------------------------- +# A contract under test, driven like the node drives it +# --------------------------------------------------------------------------------------------- +class Contract: + def __init__(self, ex, name, source, deployer, recorder): + self.ex = ex + self.name = name + self.source = source + self.deployer = deployer + self.address = key("contract:" + name) + self.bco = None + self.state = b"" + self.rec = recorder + self.methods = None + self.token_standard = None + + def compile(self): + c = self.ex.client() + r = c.compileSourceCode(self.source, EXECUTOR_VERSION) + c.close() + self.rec.step(f"{self.name}: compile", status=r.status.code, error=first_line(r.status.message), + classes=sorted(b.name for b in (r.byteCodeObjects or []))) + if r.status.code != 0: + return False + self.bco = r.byteCodeObjects + return True + + def get_methods(self): + c = self.ex.client() + r = c.getContractMethods(self.bco, EXECUTOR_VERSION) + c.close() + self.methods = {m.name: [a.type for a in m.arguments] for m in (r.methods or [])} + self.token_standard = r.tokenStandard + self.rec.step(f"{self.name}: getContractMethods", status=r.status.code, tokenStandard=r.tokenStandard, + methods=sorted(f"{m.name}({','.join(a.type for a in m.arguments)})" for m in (r.methods or []))) + return r + + def _binary(self, state, can_modify=True): + return executor.SmartContractBinary(contractAddress=self.address, + object=general.ClassObject(byteCodeObjects=self.bco, instance=state), + stateCanModify=can_modify) + + def deploy(self, timeout=None): + if self.bco is None and not self.compile(): + return None + c = self.ex.client(timeout or 120000) + try: + r = c.executeByteCode(self.ex.next_access_id(), self.deployer, self._binary(b""), [], EXECUTION_TIME, + EXECUTOR_VERSION) + except Exception as e: + self.rec.step(f"{self.name}: deploy", transport_error=type(e).__name__) + return None + finally: + c.close() + return self._take(r, "deploy") + + def call(self, initiator, method, *params, label=None): + """A transaction calling method: the node keeps the new state only when the call succeeds.""" + c = self.ex.client() + try: + r = c.executeByteCode(self.ex.next_access_id(), initiator, self._binary(self.state), + [executor.MethodHeader(methodName=method, params=list(params))], EXECUTION_TIME, + EXECUTOR_VERSION) + finally: + c.close() + return self._take(r, label or f"{method}({', '.join(json.dumps(plain(p)) for p in params)})") + + def _take(self, r, label): + if r.status.code != 0 or not r.results: + self.rec.step(f"{self.name}: {label}", status=r.status.code, error=first_line(r.status.message)) + return {"ok": False, "status": r.status.code, "error": first_line(r.status.message)} + res = r.results[0] + states = {b58(a): hashlib.sha256(s).hexdigest()[:16] for a, s in (res.contractsState or {}).items()} + emitted = [(b58(t.source), b58(t.target), t.amount.integral, t.amount.fraction) for t in (res.emittedTransactions or [])] + ok = res.status.code == 0 + if ok: + new_state = (res.contractsState or {}).get(self.address) + if new_state: + self.state = new_state + self.rec.step(f"{self.name}: {label}", status=res.status.code, ret=variant_value(res.ret_val), + error=first_line(res.status.message) if not ok else "", states=states, emitted=emitted) + return {"ok": ok, "status": res.status.code, "ret": plain(res.ret_val), "error": first_line(res.status.message), + "states": states, "emitted": emitted, "raw_states": res.contractsState or {}} + + def get(self, method, *params, initiator=None, label=None, state=None): + """A getter the way the API runs it: executeByteCodeMultiple, the state is not kept.""" + return self.get_many(method, [list(params)], initiator=initiator, label=label, state=state)[0] + + def get_many(self, method, params_list, initiator=None, label=None, state=None): + c = self.ex.client() + try: + r = c.executeByteCodeMultiple(self.ex.next_access_id(), initiator or self.deployer, + self._binary(self.state if state is None else state, False), method, + params_list, EXECUTION_TIME, EXECUTOR_VERSION) + finally: + c.close() + out = [] + if r.status.code != 0: + self.rec.step(f"{self.name}: get {label or method}", status=r.status.code, error=first_line(r.status.message)) + return [{"ok": False, "error": first_line(r.status.message)}] * len(params_list) + for res in r.results: + out.append({"ok": res.status.code == 0, "ret": plain(res.ret_val), "error": first_line(res.status.message)}) + self.rec.step(f"{self.name}: get {label or method}", results=[[o["ok"], o["ret"] if o["ok"] else o["error"]] for o in out]) + return out + + def publish(self): + """Make the current state visible to SmartContractGet (contract-to-contract calls).""" + self.ex.stub.contracts[self.address] = (self.bco, self.state) + + +class Recorder: + def __init__(self): + self.steps = [] + self.findings = [] + self.scenario = "" + + def step(self, label, **data): + self.steps.append({"scenario": self.scenario, "step": label, **data}) + + def expect(self, condition, finding, severity="bug"): + """An expectation of a scenario; a failed one is a finding about the executor's behaviour.""" + self.steps.append({"scenario": self.scenario, "expect": finding, "holds": bool(condition)}) + if not condition: + self.findings.append({"scenario": self.scenario, "severity": severity, "finding": finding}) + return condition + + +def comparable(step): + # the executor's error text carries stack traces and line numbers; the status code and the + # first line are what the node keeps (ret_val of a failed call is the message) + return json.dumps(step, sort_keys=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--jar", action="append", required=True) + parser.add_argument("--jdk", required=True) + parser.add_argument("--work", default="executor-harness-run") + parser.add_argument("--json", default="") + parser.add_argument("--only", default="") + parser.add_argument("--java-opt", action="append", default=[], + help="a JVM option for every executor, e.g. -Dcontract.executor.unbounded.code.hold.ms=20000") + args = parser.parse_args() + + sys.path.insert(0, HERE) + import token_scenarios + + scenarios = token_scenarios.SCENARIOS + if args.only: + wanted = set(args.only.split(",")) + scenarios = [s for s in scenarios if s.__name__ in wanted] + + runs = [] + for n, jar in enumerate(args.jar): + ex = Executor(jar, args.jdk, os.path.join(os.path.abspath(args.work), f"executor{n}"), args.java_opt) + ex.start() + c = ex.client() + v = c.getExecutorBuildVersion(EXECUTOR_VERSION) + c.close() + print(f"== executor {n}: {jar} (commit {v.commitNumber} {v.commitHash[:10]})", flush=True) + rec = Recorder() + try: + for scenario in scenarios: + rec.scenario = scenario.__name__ + print(f"-- {scenario.__name__}: {(scenario.__doc__ or '').strip().splitlines()[0]}", flush=True) + try: + scenario(ex, rec, Contract) + except Exception as e: # a scenario that breaks is a finding too + rec.step("scenario aborted", error=f"{type(e).__name__}: {e}") + rec.findings.append({"scenario": scenario.__name__, "severity": "harness", + "finding": f"aborted: {type(e).__name__}: {e}"}) + if ex.proc.poll() is not None: + ex.restart() + finally: + ex.stop() + runs.append({"jar": jar, "commit": v.commitNumber, "steps": rec.steps, "findings": rec.findings}) + + failures = 0 + ref = runs[0] + for run in runs: + print(f"\n== findings with {run['jar']}") + for f in run["findings"]: + print(f" [{f['severity']}] {f['scenario']}: {f['finding']}") + for other in runs[1:]: + a = [comparable(s) for s in ref["steps"]] + b = [comparable(s) for s in other["steps"]] + diffs = [(i, x, y) for i, (x, y) in enumerate(zip(a, b)) if x != y] + if len(a) != len(b): + diffs.append((min(len(a), len(b)), f"{len(a)} steps", f"{len(b)} steps")) + print(f"\n== {other['jar']} against {ref['jar']}: {len(diffs)} differing steps") + for i, x, y in diffs[:40]: + print(f" step {i}:\n ref: {x[:400]}\n other: {y[:400]}") + failures += 1 if diffs else 0 + if args.json: + with open(args.json, "w") as f: + json.dump(runs, f, indent=1) + sys.exit(1 if failures else 0) + + +if __name__ == "__main__": + main() diff --git a/ci/contracts/token_scenarios.py b/ci/contracts/token_scenarios.py new file mode 100644 index 000000000..dfae04d74 --- /dev/null +++ b/ci/contracts/token_scenarios.py @@ -0,0 +1,540 @@ +"""Token scenarios for executor_harness.py. + +Each scenario gets the executor, the recorder and the Contract class. It drives contracts the way +the node does and states what a token user expects with rec.expect(): an expectation that does not +hold is a finding about the platform (the executor, or the way the node and the API use it). +""" +import os + +from executor_harness import b58, key, plain, v_bool, v_bytes, v_dec, v_str + +HERE = os.path.dirname(os.path.abspath(__file__)) + +OWNER = key("owner") +ALICE = key("alice") +BOB = key("bob") +CAROL = key("carol") + + +def source(name): + with open(os.path.join(HERE, "tokens", name + ".java")) as f: + return f.read() + + +BASIC_V0 = """import com.credits.scapi.v0.BasicStandard; +import com.credits.scapi.v0.SmartContract; + +public class BasicV0 extends SmartContract implements BasicStandard { + public BasicV0() { super(); } + public String getName() { return "Basic V0"; } + public String getSymbol() { return "BV0"; } + public int getDecimal() { return 0; } + public boolean setFrozen(boolean frozen) { return false; } + public String totalSupply() { return "1"; } + public String balanceOf(String owner) { return "0"; } + public String allowance(String owner, String spender) { return "0"; } + public boolean transfer(String to, String amount) { return true; } + public boolean transferFrom(String from, String to, String amount) { return true; } + public void approve(String spender, String amount) { } + public boolean burn(String amount) { return true; } +} +""" + +BASIC_V1 = """import com.credits.scapi.v1.BasicTokenStandard; +import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class BasicV1 extends SmartContract implements BasicTokenStandard { + public BasicV1() { super(); } + public String getName() { return "Basic V1"; } + public String getSymbol() { return "BV1"; } + public int getDecimal() { return 0; } + public boolean setFrozen(boolean frozen) { return false; } + public BigDecimal totalSupply() { return BigDecimal.ONE; } + public BigDecimal balanceOf(String owner) { return BigDecimal.ZERO; } + public BigDecimal allowance(String owner, String spender) { return BigDecimal.ZERO; } + public boolean transfer(String to, BigDecimal amount) { return true; } + public boolean transferFrom(String from, String to, BigDecimal amount) { return true; } + public void approve(String spender, BigDecimal amount) { } + public boolean burn(BigDecimal amount) { return true; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# the v2 token standard of sc-api-support: balances exposed as an ObservableMap +BASIC_V2 = """import com.credits.scapi.v2.BasicTokenStandard; +import com.credits.scapi.v2.MapChangeListener; +import com.credits.scapi.v2.ObservableMap; +import com.credits.scapi.v2.WalletAddress; +import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; +import java.util.HashMap; + +public class BasicV2 extends SmartContract implements BasicTokenStandard { + public static class Balances extends HashMap implements ObservableMap { + public void addListener(MapChangeListener l) { } + public void removeListener(MapChangeListener l) { } + } + private final Balances balances = new Balances(); + public BasicV2() { super(); } + public ObservableMap getTokenBalances() { return balances; } + public String getName() { return "Basic V2"; } + public String getSymbol() { return "BV2"; } + public int getDecimal() { return 0; } + public boolean setFrozen(boolean frozen) { return false; } + public BigDecimal totalSupply() { return BigDecimal.ONE; } + public BigDecimal balanceOf(String owner) { return BigDecimal.ZERO; } + public BigDecimal allowance(String owner, String spender) { return BigDecimal.ZERO; } + public boolean transfer(String to, BigDecimal amount) { return true; } + public boolean transferFrom(String from, String to, BigDecimal amount) { return true; } + public void approve(String spender, BigDecimal amount) { } + public boolean burn(BigDecimal amount) { return true; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# a token whose standard comes from a base class, as code reuse makes common elsewhere +INHERITED = """import com.credits.scapi.v1.BasicTokenStandard; +import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class Inherited extends TokenBase { + public Inherited() { super(); } + public String getName() { return "Inherited"; } + public String getSymbol() { return "INH"; } +} + +abstract class TokenBase extends SmartContract implements BasicTokenStandard { + public int getDecimal() { return 0; } + public boolean setFrozen(boolean frozen) { return false; } + public BigDecimal totalSupply() { return BigDecimal.ONE; } + public BigDecimal balanceOf(String owner) { return BigDecimal.ZERO; } + public BigDecimal allowance(String owner, String spender) { return BigDecimal.ZERO; } + public boolean transfer(String to, BigDecimal amount) { return true; } + public boolean transferFrom(String from, String to, BigDecimal amount) { return true; } + public void approve(String spender, BigDecimal amount) { } + public boolean burn(BigDecimal amount) { return true; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# the reserved name check of the deploy, for every token interface +def reserved(cls, iface, smart, sig_amount): + imports = {"v0": "import com.credits.scapi.v0.BasicStandard;", + "v1": "import com.credits.scapi.v1.BasicTokenStandard;", + "v2": "import com.credits.scapi.v2.BasicTokenStandard;\nimport com.credits.scapi.v2.ObservableMap;\nimport com.credits.scapi.v2.WalletAddress;"}[iface] + name = {"v0": "BasicStandard", "v1": "BasicTokenStandard", "v2": "BasicTokenStandard"}[iface] + t = sig_amount + ret = "String" if t == "String" else "BigDecimal" + zero = '"0"' if t == "String" else "BigDecimal.ZERO" + extra = "" + if iface == "v2": + extra = "public ObservableMap getTokenBalances() { return null; }\n" + if iface != "v0": + extra += "public String payable(BigDecimal amount, byte[] userData) { return \"ok\"; }\n" + return f"""{imports} +import com.credits.scapi.{smart}.SmartContract; +import java.math.BigDecimal; + +public class {cls} extends SmartContract implements {name} {{ + public {cls}() {{ super(); }} + public String getName() {{ return "CS Credits"; }} + public String getSymbol() {{ return "CS"; }} + public int getDecimal() {{ return 18; }} + public boolean setFrozen(boolean frozen) {{ return false; }} + public {ret} totalSupply() {{ return {zero}; }} + public {ret} balanceOf(String owner) {{ return {zero}; }} + public {ret} allowance(String owner, String spender) {{ return {zero}; }} + public boolean transfer(String to, {t} amount) {{ return true; }} + public boolean transferFrom(String from, String to, {t} amount) {{ return true; }} + public void approve(String spender, {t} amount) {{ }} + public boolean burn({t} amount) {{ return true; }} + {extra} +}} +""" + + +# a method that changes the state and then fails, as a transfer that checks too late does +PARTIAL = """import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; +import java.util.HashMap; + +public class Partial extends SmartContract { + private final HashMap balances = new HashMap<>(); + private int calls; + public Partial() { super(); balances.put(initiator, 100); } + public int debitThenFail(int amount) { + calls += 1; + balances.put(initiator, balances.getOrDefault(initiator, 0) - amount); + sendTransaction(contractAddress, initiator, 1.0); + throw new RuntimeException("checked too late"); + } + public int balance(String who) { return balances.getOrDefault(who, 0); } + public int calls() { return calls; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# a getter that writes: the API runs getters with stateCanModify = false +GETTER_WRITES = """import com.credits.scapi.annotations.Getter; +import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class GetterWrites extends SmartContract { + private int reads; + public GetterWrites() { super(); } + @Getter + public int read() { reads += 1; return reads; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# two top-level classes: the executor takes "any" class without '$' in its name as the contract +TWO_CLASSES = """import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class Main extends SmartContract { + private int value = 7; + public Main() { super(); } + public int value() { return value; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} + +class Helper { + public int value() { return -1; } +} +""" + +# what a token can learn from the platform: seed, block time, CS balances, emitted transactions +PLATFORM = """import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class Platform extends SmartContract { + private String last = ""; + public Platform() { super(); } + public String seed() { byte[] s = getSeed(); return s == null ? "null" : Integer.toString(s.length); } + public long time() { return getBlockchainTimeMills(); } + public String balance(String who) { return getBalance(who).toPlainString(); } + public String whoami() { last = initiator + "|" + contractAddress; return last; } + public boolean pay(String to, double amount) { sendTransaction(contractAddress, to, amount); return true; } + public boolean payFrom(String from, String to, double amount) { sendTransaction(from, to, amount); return true; } + public String payable(BigDecimal amount, byte[] userData) { return amount.toPlainString() + "/" + userData.length; } +} +""" + +# contract-to-contract: a shop that pays with the tokens it holds +SHOP = """import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class Shop extends SmartContract { + private final String token; + public Shop() { super(); token = "%s"; } + public Object pay(String to, BigDecimal amount) { return invokeExternalContract(token, "transfer", to, amount); } + public Object myBalance() { return invokeExternalContract(token, "balanceOf", contractAddress); } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# a token whose getName never returns: the deploy calls getName outside the time limit +SLOW_NAME = """import com.credits.scapi.v0.BasicStandard; +import com.credits.scapi.v0.SmartContract; + +public class SlowName extends SmartContract implements BasicStandard { + public SlowName() { super(); } + public String getName() { long x = 0; while (true) { x++; if (x < 0) return "never"; } } + public String getSymbol() { return "SLOW"; } + public int getDecimal() { return 0; } + public boolean setFrozen(boolean frozen) { return false; } + public String totalSupply() { return "1"; } + public String balanceOf(String owner) { return "0"; } + public String allowance(String owner, String spender) { return "0"; } + public boolean transfer(String to, String amount) { return true; } + public boolean transferFrom(String from, String to, String amount) { return true; } + public void approve(String spender, String amount) { } + public boolean burn(String amount) { return true; } +} +""" + + +# a state whose serialization never ends: the executor serializes the new state outside the +# contract's time limit +SERIAL_LOOP = """import com.credits.scapi.v3.SmartContract; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.math.BigDecimal; + +public class SerialLoop extends SmartContract { + public static class Payload implements Serializable { + private boolean armed; + private void writeObject(ObjectOutputStream out) throws IOException { + long x = 0; + while (armed) { x++; if (x < 0) break; } + out.defaultWriteObject(); + } + } + private final Payload payload = new Payload(); + public SerialLoop() { super(); } + public boolean arm() { payload.armed = true; return true; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + +# a double amount the CS Amount cannot hold exactly +PRECISION = """import com.credits.scapi.v3.SmartContract; +import java.math.BigDecimal; + +public class Precision extends SmartContract { + public Precision() { super(); } + public boolean pay(String to, BigDecimal amount) { sendTransaction(contractAddress, to, amount.doubleValue()); return true; } + public String payable(BigDecimal amount, byte[] userData) { return "ok"; } +} +""" + + +# --------------------------------------------------------------------------------------------- +def token_standards(ex, rec, Contract): + """The token standard getContractMethods reports for each kind of token""" + expected = [("BasicV0", BASIC_V0, 1), ("TokenV0", source("TokenV0"), 2), ("BasicV1", BASIC_V1, 3), + ("TokenV1", source("TokenV1"), 4), ("BasicV2", BASIC_V2, None), ("Inherited", INHERITED, None)] + for name, src, ts in expected: + c = Contract(ex, name, src, OWNER, rec) + # a token standard from a base class needs a second top-level class, which the executor's + # compiler refuses ("Class name not found"): only one top-level class per contract + if not rec.expect(c.compile(), f"{name} compiles", severity="info" if name == "Inherited" else "bug"): + continue + r = c.get_methods() + if ts is not None: + rec.expect(r.tokenStandard == ts, f"{name} reports token standard {ts} (got {r.tokenStandard})") + else: + rec.expect(r.tokenStandard != 0, f"{name} is reported as a token (got {r.tokenStandard}): the API ignores " + f"tokens reported as 0") + + +def token_v1_lifecycle(ex, rec, Contract): + """A v1 token through deploy, getters, transfer, approve/transferFrom, burn, freeze""" + t = Contract(ex, "TokenV1", source("TokenV1"), OWNER, rec) + d = t.deploy() + if not rec.expect(d and d["ok"], "TokenV1 deploys"): + return + get = lambda m, *p: t.get(m, *p)["ret"] + rec.expect(get("getName") == "Test Token V1", "getName as a getter") + rec.expect(get("balanceOf", v_str(b58(OWNER))) == "10000000.000", "the owner holds the supply") + + # a wallet that builds the call from the declared types sends a BigDecimal + r = t.call(OWNER, "transfer", v_str(b58(ALICE)), v_dec("1500.5")) + rec.expect(r["ok"] and r["ret"] is True, "transfer(String, BigDecimal) with a v_big_decimal amount") + rec.expect(get("balanceOf", v_str(b58(ALICE))) == "1500.500", "Alice's balance after the transfer") + + # the API's token cache recognises a transfer only when both arguments are strings + r = t.call(OWNER, "transfer", v_str(b58(ALICE)), v_str("10"), label="transfer(alice, \"10\") amount as a string") + rec.expect(r["ok"], "a v1 transfer with the amount as a string (what the API's token cache expects) is accepted", + severity="interop") + + # scale: BigDecimal keeps the scale it is given, balances may end up as 1500.5 vs 1500.500 + r = t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("0.0001")) + rec.expect(r["ok"], "a transfer below the token's decimals is accepted by this token", severity="info") + rec.expect(get("balanceOf", v_str(b58(BOB))) == "0.0001", + "the token keeps the amount's own scale (0.0001 with 3 decimals): the contract must round", + severity="info") + + r = t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("999999")) + rec.expect(not r["ok"], "a transfer above the balance fails") + rec.expect("enough tokens" in r["error"] or "enough tokens" in str(r.get("ret")), "its error reaches the caller") + + r = t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("-5")) + rec.expect(not r["ok"], "a negative transfer fails (the contract checks it)") + + r = t.call(OWNER, "approve", v_str(b58(BOB)), v_dec("100")) + rec.expect(r["ok"], "approve") + rec.expect(get("allowance", v_str(b58(OWNER)), v_str(b58(BOB))) == "100", "allowance after approve") + r = t.call(BOB, "transferFrom", v_str(b58(OWNER)), v_str(b58(CAROL)), v_dec("60")) + rec.expect(r["ok"], "transferFrom within the allowance") + r = t.call(BOB, "transferFrom", v_str(b58(OWNER)), v_str(b58(CAROL)), v_dec("60")) + rec.expect(not r["ok"], "transferFrom above the allowance fails") + rec.expect(get("balanceOf", v_str(b58(CAROL))) == "60.000", "Carol's balance") + + r = t.call(ALICE, "setFrozen", v_bool(True)) + rec.expect(not r["ok"], "only the owner freezes") + r = t.call(OWNER, "setFrozen", v_bool(True)) + rec.expect(r["ok"], "the owner freezes") + r = t.call(ALICE, "transfer", v_str(b58(BOB)), v_dec("1")) + rec.expect(not r["ok"], "no transfer while frozen") + t.call(OWNER, "setFrozen", v_bool(False)) + + r = t.call(OWNER, "burn", v_dec("1000")) + rec.expect(r["ok"] and get("totalSupply") == "9999000.000", "burn lowers the supply") + r = t.call(CAROL, "register") + rec.expect(r["ok"], "register") + + # the API refreshes every holder's balance with one executeByteCodeMultiple + holders = [OWNER, ALICE, BOB, CAROL] + [key(f"h{i}") for i in range(50)] + many = t.get_many("balanceOf", [[v_str(b58(h))] for h in holders], label="balanceOf x54") + rec.expect(all(m["ok"] for m in many), "balanceOf for 54 holders in one executeByteCodeMultiple") + + # the node calls payable(BigDecimal, byte[]) for a CS transfer to a payable contract + r = t.call(ALICE, "payable", v_dec("25.5"), v_bytes(b""), label="payable(25.5, []) as the node sends it") + rec.expect(r["ok"] and get("balanceOf", v_str(b58(ALICE))) == "1525.9999", "payable buys tokens", + severity="info") + + r = t.call(ALICE, "sell", v_dec("0.1")) + rec.expect(r["ok"] and len(r["emitted"]) == 1, "sell emits one CS transaction") + if r["ok"] and r["emitted"]: + rec.expect(r["emitted"][0][2:] == [0, 100000000000000000] or tuple(r["emitted"][0][2:]) == (0, 100000000000000000), + f"0.1 CS emitted exactly (got {r['emitted'][0][2:]}): sendTransaction takes a double", + severity="info") + + +def token_v0_lifecycle(ex, rec, Contract): + """A v0 token (amounts as strings), including the legacy payable(String, String)""" + t = Contract(ex, "TokenV0", source("TokenV0"), OWNER, rec) + d = t.deploy() + if not rec.expect(d and d["ok"], "TokenV0 deploys"): + return + r = t.call(OWNER, "transfer", v_str(b58(ALICE)), v_str("12.34")) + rec.expect(r["ok"], "transfer(String, String)") + r = t.call(OWNER, "transfer", v_str(b58(ALICE)), v_dec("1"), label="transfer(alice, 1) amount as a BigDecimal") + rec.expect(r["ok"], "a v0 transfer with a v_big_decimal amount is accepted", severity="interop") + rec.expect(t.get("balanceOf", v_str(b58(ALICE)))["ret"] == "12.34", "balance as a string") + r = t.call(ALICE, "payable", v_str("3"), v_str(""), label="payable(\"3\", \"\") legacy convention") + rec.expect(r["ok"], "legacy payable(String, String)") + + +def failed_call_state(ex, rec, Contract): + """What the executor returns for a call that changes the state and then throws""" + p = Contract(ex, "Partial", PARTIAL, OWNER, rec) + if not rec.expect((p.deploy() or {}).get("ok"), "Partial deploys"): + return + before = p.state + r = p.call(OWNER, "debitThenFail", general_int(10)) + rec.expect(not r["ok"], "the call fails") + rec.expect(not r["states"], f"a failed call returns no contract state (got {r['states']}); the node must not " + "keep it", severity="info") + rec.expect(not r["emitted"], f"a failed call returns no emitted transaction (got {r['emitted']})", severity="info") + rec.expect(p.get("balance", v_str(b58(OWNER)))["ret"] == 100 and p.state == before, + "the state the node keeps is unchanged") + + +def getter_writes(ex, rec, Contract): + """A getter that changes the state, run as the API runs getters""" + g = Contract(ex, "GetterWrites", GETTER_WRITES, OWNER, rec) + if not rec.expect((g.deploy() or {}).get("ok"), "GetterWrites deploys"): + return + r1 = g.get("read") + r2 = g.get("read") + rec.expect(r1["ok"] and r2["ok"] and r1["ret"] == r2["ret"] == 1, + "a getter that writes runs on a copy: every read starts from the stored state", severity="info") + + +def reserved_names(ex, rec, Contract): + """The deploy refuses the name "CS Credits" and the symbol "CS" for every token standard""" + for cls, iface, smart, t in (("ReservedV0", "v0", "v0", "String"), ("ReservedV1", "v1", "v3", "BigDecimal"), + ("ReservedV2", "v2", "v3", "BigDecimal")): + c = Contract(ex, cls, reserved(cls, iface, smart, t), OWNER, rec) + d = c.deploy() + rec.expect(d is not None and not d["ok"], f"{cls} ({iface} standard) named CS is refused at deploy", + severity="bug" if iface != "v2" else "gap") + + +def root_class(ex, rec, Contract): + """A source with two top-level classes: which one is the contract""" + m = Contract(ex, "Main", TWO_CLASSES, OWNER, rec) + d = m.deploy() + rec.expect(d and d["ok"], "a contract with a helper class deploys", severity="info") + if d and d["ok"]: + rec.expect(m.get("value")["ret"] == 7, "the public class is the contract", severity="bug") + + +def platform_calls(ex, rec, Contract): + """Seed, block time, CS balance, initiator, emitted transactions""" + p = Contract(ex, "Platform", PLATFORM, OWNER, rec) + if not rec.expect((p.deploy() or {}).get("ok"), "Platform deploys"): + return + ex.stub.balances[ALICE] = (12, 500000000000000000) + rec.expect(p.call(ALICE, "seed")["ret"] == "32", "getSeed in a call") + rec.expect(p.call(ALICE, "time")["ok"], "getBlockchainTimeMills in a call") + rec.expect(p.call(ALICE, "balance", v_str(b58(ALICE)))["ret"] == "12.5", "getBalance", severity="info") + r = p.call(ALICE, "whoami") + rec.expect(r["ret"] == b58(ALICE) + "|" + b58(p.address), "initiator and contractAddress") + r = p.call(ALICE, "payFrom", v_str(b58(ALICE)), v_str(b58(BOB)), general_double(1.0)) + rec.expect(r["ok"], "the executor accepts an emitted transaction from another wallet (the node drops it)", + severity="info") + r = p.call(ALICE, "payable", v_dec("1.5"), v_bytes(b"hi")) + rec.expect(r["ret"] == "1.5/2", "payable with user data") + + +def contract_calls(ex, rec, Contract): + """A contract that moves tokens through invokeExternalContract (refused by the node today)""" + token = Contract(ex, "TokenV1c", source("TokenV1").replace("class TokenV1 ", "class TokenV1c ") + .replace("public TokenV1()", "public TokenV1c()"), OWNER, rec) + if not rec.expect((token.deploy() or {}).get("ok"), "token deploys"): + return + shop = Contract(ex, "Shop", SHOP % b58(token.address), OWNER, rec) + if not rec.expect((shop.deploy() or {}).get("ok"), "Shop deploys"): + return + token.call(OWNER, "transfer", v_str(b58(shop.address)), v_dec("100")) + token.publish() + shop.publish() + r = shop.call(ALICE, "pay", v_str(b58(BOB)), v_dec("10")) + rec.expect(r["ok"], f"a contract transfers the tokens it holds (error: {r['error']})", severity="gap") + if r["ok"]: + rec.expect(b58(token.address) in r["states"], "the token's new state is returned with the caller's") + + +def slow_token_name(ex, rec, Contract): + """A token whose getName() never returns: the reserved-name check runs it without a time limit""" + s = Contract(ex, "SlowName", SLOW_NAME, OWNER, rec) + d = s.deploy(timeout=40000) + rec.expect(d is not None, "the deploy of a token whose getName() loops answers within 40 s", severity="security") + probe = Contract(ex, "BasicV0probe", BASIC_V0.replace("BasicV0", "BasicV0probe"), OWNER, rec) + try: + ok = probe.compile() + except Exception: + ok = False + rec.expect(ok, "the executor still answers afterwards", severity="security") + + +def serialization_hang(ex, rec, Contract): + """A state whose writeObject() loops once armed: serialization runs outside the time limit""" + s = Contract(ex, "SerialLoop", SERIAL_LOOP, OWNER, rec) + if not rec.expect((s.deploy() or {}).get("ok"), "SerialLoop deploys"): + return + c = ex.client(40000) + try: + from executor_harness import EXECUTION_TIME, EXECUTOR_VERSION, executor + c.executeByteCode(ex.next_access_id(), ALICE, s._binary(s.state), [executor.MethodHeader(methodName="arm", params=[])], + EXECUTION_TIME, EXECUTOR_VERSION) + answered = True + except Exception: + answered = False + finally: + c.close() + rec.expect(answered, "a call whose new state never finishes serializing answers within 40 s", severity="security") + + +def emitted_precision(ex, rec, Contract): + """CS amounts a contract emits go through a double""" + p = Contract(ex, "Precision", PRECISION, OWNER, rec) + if not rec.expect((p.deploy() or {}).get("ok"), "Precision deploys"): + return + for amount, want in (("0.1", (0, 100000000000000000)), ("1234567.123456789012345678", (1234567, 123456789012345678)), + ("0.000000000000000001", (0, 1))): + r = p.call(ALICE, "pay", v_str(b58(BOB)), v_dec(amount)) + got = tuple(r["emitted"][0][2:]) if r["ok"] and r["emitted"] else None + rec.expect(got == want, f"emitting {amount} CS gives {want} (got {got}): sendTransaction takes a double", + severity="info") + + +def general_int(i): + from executor_harness import v_int + return v_int(i) + + +def general_double(x): + from executor_harness import general + return general.Variant(v_double=x) + + +SCENARIOS = [token_standards, token_v1_lifecycle, token_v0_lifecycle, failed_call_state, getter_writes, + reserved_names, root_class, platform_calls, emitted_precision, contract_calls, slow_token_name, + serialization_hang] diff --git a/ci/contracts/tokens/TokenV0.java b/ci/contracts/tokens/TokenV0.java new file mode 100644 index 000000000..30f8fc20b --- /dev/null +++ b/ci/contracts/tokens/TokenV0.java @@ -0,0 +1,155 @@ +import com.credits.scapi.v0.ExtensionStandard; +import com.credits.scapi.v0.SmartContract; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import static java.math.BigDecimal.ROUND_DOWN; +import static java.math.BigDecimal.ZERO; + +// A first generation token: SmartContract v0 and ExtensionStandard v0, amounts passed as strings. +public class TokenV0 extends SmartContract implements ExtensionStandard { + + private final String owner; + private final int decimal = 2; + private final HashMap balances = new HashMap<>(); + private final HashMap> allowed = new HashMap<>(); + private BigDecimal totalCoins; + private boolean frozen; + + public TokenV0() { + super(); + owner = initiator; + totalCoins = new BigDecimal(1_000_000).setScale(decimal, ROUND_DOWN); + balances.put(owner, totalCoins); + } + + @Override + public String getName() { + return "Test Token V0"; + } + + @Override + public String getSymbol() { + return "TTV0"; + } + + @Override + public int getDecimal() { + return decimal; + } + + @Override + public boolean setFrozen(boolean isFrozen) { + if (!initiator.equals(owner)) { + throw new RuntimeException("not the owner"); + } + frozen = isFrozen; + return true; + } + + @Override + public String totalSupply() { + return totalCoins.toString(); + } + + @Override + public String balanceOf(String owner) { + return get(owner).toString(); + } + + @Override + public String allowance(String owner, String spender) { + Map spenders = allowed.get(owner); + BigDecimal amount = spenders == null ? null : spenders.get(spender); + return (amount == null ? ZERO : amount).toString(); + } + + @Override + public boolean transfer(String to, String amount) { + notFrozen(); + BigDecimal value = parse(amount); + BigDecimal from = get(initiator); + if (from.compareTo(value) < 0) { + throw new RuntimeException("not enough tokens"); + } + balances.put(initiator, from.subtract(value)); + balances.put(to, get(to).add(value)); + return true; + } + + @Override + public boolean transferFrom(String from, String to, String amount) { + notFrozen(); + BigDecimal value = parse(amount); + Map spenders = allowed.get(from); + BigDecimal allow = spenders == null ? null : spenders.get(initiator); + if (allow == null || allow.compareTo(value) < 0) { + throw new RuntimeException("not approved"); + } + BigDecimal source = get(from); + if (source.compareTo(value) < 0) { + throw new RuntimeException("not enough tokens"); + } + spenders.put(initiator, allow.subtract(value)); + balances.put(from, source.subtract(value)); + balances.put(to, get(to).add(value)); + return true; + } + + @Override + public void approve(String spender, String amount) { + allowed.computeIfAbsent(initiator, k -> new HashMap<>()).put(spender, parse(amount)); + } + + @Override + public boolean burn(String amount) { + BigDecimal value = parse(amount); + BigDecimal balance = get(initiator); + if (balance.compareTo(value) < 0) { + throw new RuntimeException("not enough tokens"); + } + balances.put(initiator, balance.subtract(value)); + totalCoins = totalCoins.subtract(value); + return true; + } + + @Override + public void register() { + balances.putIfAbsent(initiator, ZERO.setScale(decimal, ROUND_DOWN)); + } + + @Override + public boolean buyTokens(String amount) { + return false; + } + + // the payable() of the first API version: amount and user data as strings + public String payable(String amount, String currency) { + BigDecimal value = parse(amount); + BigDecimal ownerBalance = get(owner); + balances.put(owner, ownerBalance.subtract(value)); + balances.put(initiator, get(initiator).add(value)); + return "bought " + value; + } + + private void notFrozen() { + if (frozen) { + throw new RuntimeException("frozen"); + } + } + + private BigDecimal parse(String amount) { + BigDecimal value = new BigDecimal(amount.replace(',', '.')).setScale(decimal, ROUND_DOWN); + if (value.signum() < 0) { + throw new RuntimeException("negative amount"); + } + return value; + } + + private BigDecimal get(String address) { + BigDecimal balance = balances.get(address); + return balance != null ? balance : ZERO.setScale(decimal, ROUND_DOWN); + } +} diff --git a/ci/contracts/tokens/TokenV1.java b/ci/contracts/tokens/TokenV1.java new file mode 100644 index 000000000..1835dc7ae --- /dev/null +++ b/ci/contracts/tokens/TokenV1.java @@ -0,0 +1,210 @@ +import com.credits.scapi.annotations.Getter; +import com.credits.scapi.v1.ExtensionTokenStandard; +import com.credits.scapi.v3.SmartContract; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import static java.math.BigDecimal.ROUND_DOWN; +import static java.math.BigDecimal.ZERO; + +// A token written the way current Credits tokens are: SmartContract v3 and ExtensionTokenStandard v1 +// (BigDecimal amounts), balances in a HashMap keyed by the base58 address, CS bought through payable(). +public class TokenV1 extends SmartContract implements ExtensionTokenStandard { + + private final String owner; + private final int decimal; + private final BigDecimal tokenCost; + private final HashMap balances; + private final HashMap> allowed; + private final String name; + private final String symbol; + private BigDecimal totalCoins; + private boolean frozen; + + public TokenV1() { + super(); + name = "Test Token V1"; + symbol = "TTV1"; + decimal = 3; + tokenCost = new BigDecimal(1).setScale(decimal, ROUND_DOWN); + totalCoins = new BigDecimal(10_000_000).setScale(decimal, ROUND_DOWN); + owner = initiator; + allowed = new HashMap<>(); + balances = new HashMap<>(); + balances.put(owner, totalCoins); + } + + @Getter + @Override + public int getDecimal() { + return decimal; + } + + @Override + public boolean setFrozen(boolean isFrozen) { + if (!initiator.equals(owner)) { + throw new RuntimeException("unable change frozen state! The wallet " + initiator + " is not owner"); + } + frozen = isFrozen; + return true; + } + + @Getter + @Override + public String getName() { + return name; + } + + @Getter + @Override + public String getSymbol() { + return symbol; + } + + @Getter + @Override + public BigDecimal totalSupply() { + return totalCoins; + } + + @Getter + @Override + public BigDecimal balanceOf(String owner) { + return getTokensBalance(owner); + } + + @Getter + @Override + public BigDecimal allowance(String owner, String spender) { + Map spenders = allowed.get(owner); + if (spenders == null) { + return ZERO; + } + BigDecimal amount = spenders.get(spender); + return amount != null ? amount : ZERO; + } + + @Override + public boolean transfer(String to, BigDecimal amount) { + contractIsNotFrozen(); + checkAmount(amount); + if (!to.equals(initiator)) { + BigDecimal sourceBalance = getTokensBalance(initiator); + BigDecimal targetBalance = getTokensBalance(to); + if (sourceBalance.compareTo(amount) < 0) { + throw new RuntimeException("the wallet " + initiator + " doesn't have enough tokens to transfer"); + } + balances.put(initiator, sourceBalance.subtract(amount)); + balances.put(to, targetBalance.add(amount)); + } + return true; + } + + @Override + public boolean transferFrom(String from, String to, BigDecimal amount) { + contractIsNotFrozen(); + checkAmount(amount); + if (!from.equals(to)) { + BigDecimal sourceBalance = getTokensBalance(from); + BigDecimal targetBalance = getTokensBalance(to); + if (sourceBalance.compareTo(amount) < 0) { + throw new RuntimeException("unable transfer tokens! The balance of " + from + " less then " + amount); + } + Map spenders = allowed.get(from); + if (spenders == null || !spenders.containsKey(initiator)) { + throw new RuntimeException("unable transfer tokens! The value of approved tokens is null"); + } + BigDecimal allowTokens = spenders.get(initiator); + if (allowTokens.compareTo(amount) < 0) { + throw new RuntimeException("unable transfer tokens! The value of approved tokens is less then " + amount); + } + spenders.put(initiator, allowTokens.subtract(amount)); + balances.put(from, sourceBalance.subtract(amount)); + balances.put(to, targetBalance.add(amount)); + } + return true; + } + + @Override + public void approve(String spender, BigDecimal amount) { + checkAmount(amount); + allowed.computeIfAbsent(initiator, k -> new HashMap<>()).put(spender, amount); + } + + @Override + public boolean burn(BigDecimal amount) { + contractIsNotFrozen(); + checkAmount(amount); + BigDecimal balance = getTokensBalance(initiator); + if (balance.compareTo(amount) < 0) { + throw new RuntimeException("the wallet " + initiator + " doesn't have enough tokens to burn"); + } + balances.put(initiator, balance.subtract(amount)); + totalCoins = totalCoins.subtract(amount); + return true; + } + + @Override + public void register() { + balances.putIfAbsent(initiator, ZERO.setScale(decimal, ROUND_DOWN)); + } + + @Override + public String payable(BigDecimal amount, byte[] userData) { + contractIsNotFrozen(); + if (amount.compareTo(ZERO) <= 0) { + throw new RuntimeException("amount must be positive"); + } + BigDecimal tokens = amount.divide(tokenCost, decimal, ROUND_DOWN); + BigDecimal ownerBalance = getTokensBalance(owner); + if (ownerBalance.compareTo(tokens) < 0) { + throw new RuntimeException("not enough tokens left to sell"); + } + balances.put(owner, ownerBalance.subtract(tokens)); + balances.put(initiator, getTokensBalance(initiator).add(tokens)); + return "bought " + tokens.toPlainString() + " " + symbol; + } + + // sells tokens back to the contract for CS, through a transaction the contract emits + public boolean sell(BigDecimal amount) { + contractIsNotFrozen(); + checkAmount(amount); + BigDecimal balance = getTokensBalance(initiator); + if (balance.compareTo(amount) < 0) { + throw new RuntimeException("not enough tokens"); + } + balances.put(initiator, balance.subtract(amount)); + balances.put(owner, getTokensBalance(owner).add(amount)); + sendTransaction(contractAddress, initiator, amount.multiply(tokenCost).doubleValue()); + return true; + } + + @Getter + public String getOwner() { + return owner; + } + + @Getter + public int holders() { + return balances.size(); + } + + private void contractIsNotFrozen() { + if (frozen) { + throw new RuntimeException("unavailable action! The smart-contract is frozen"); + } + } + + private void checkAmount(BigDecimal amount) { + if (amount == null || amount.signum() < 0) { + throw new RuntimeException("amount must not be negative"); + } + } + + private BigDecimal getTokensBalance(String address) { + BigDecimal balance = balances.get(address); + return balance != null ? balance : ZERO.setScale(decimal, ROUND_DOWN); + } +} diff --git a/ci/testnet/run.sh b/ci/testnet/run.sh index 578b592f2..e15621dcd 100755 --- a/ci/testnet/run.sh +++ b/ci/testnet/run.sh @@ -36,6 +36,11 @@ # contract scenario never kills, partitions or slows n1 # SYNC_CONTRACT_EXECUTION=0: every node runs with sync_contract_execution=false (no contract # re-execution while reading the blockchain; states fetched from the confidants once live) +# TOKENS=1 (with CONTRACTS): tokens.py also deploys a v1 and a v0 token from the wallet of the +# last node once fund.py's load is over, runs transfers, approvals, payable and a sale through +# n1, and checks the balances on every node, the states, and the token API of n1 (an API +# mismatch is reported; TOKENS_STRICT_API=1 fails the run on it); TOKENS_VIA=N sends them +# through node N instead (e.g. the node of the restart test, once it restarted) # CONTRACT_DICE=1 (with CONTRACTS): also a Dice contract that reads its own balance, played three # times before the restart test; a node that syncs through the plays re-executes them # CONTRACT_LOAD_SECONDS (default 0, with CONTRACTS): after the calls, a load phase of that many @@ -239,6 +244,9 @@ JOIN_FULL=${JOIN_FULL:-0} CONTRACTS=${CONTRACTS:-0} CONTRACTS_AFTER_AT=${CONTRACTS_AFTER_AT:-0} CONTRACT_DICE=${CONTRACT_DICE:-0} +TOKENS=${TOKENS:-0} +TOKENS_STRICT_API=${TOKENS_STRICT_API:-0} +TOKENS_VIA=${TOKENS_VIA:-1} SYNC_CONTRACT_EXECUTION=${SYNC_CONTRACT_EXECUTION:-1} [ "$CONTRACTS_AFTER_AT" -eq 0 ] || [ "$CONTRACTS_AFTER_AT" -le $(( ${TARGET_SEQ:-1100} - 100 )) ] \ || { echo "CONTRACTS_AFTER_AT must be at most TARGET_SEQ - 100"; exit 1; } @@ -507,6 +515,8 @@ api_settings() { echo "executor_port=$((9300 + i))" echo "executor_command=$WORK/n$i/executor.sh" echo "executor_multi_instance=true" + # the token cache behind the Token* API methods (read by builds that have the key) + [ "$TOKENS" != "1" ] || echo "tokens_cache=true" # the first contract compile in a fresh JVM takes longer than the 4 s default echo "executor_send_timeout=60000" echo "executor_receive_timeout=60000" @@ -833,6 +843,7 @@ crash_next=0 crashed_all=0 FUND_PID= CONTRACTS_PID= +TOKENS_PID= disk_filled_at=0 disk_freed=0 net_fault_at=0 @@ -1381,6 +1392,13 @@ PY --stats-file "$WORK/contracts-stats.json" $([ "$CONTRACT_DICE" = 1 ] && echo --dice)) > "$WORK/contracts.log" 2>&1 & CONTRACTS_PID=$! fi + if [ "$TOKENS" = "1" ] && [ "$CONTRACTS" = "1" ] && [ -z "$TOKENS_PID" ] && grep -q "load transfers sent" "$WORK/fund.log" 2>/dev/null \ + && { [ "$TOKENS_VIA" -eq 1 ] || [ "$RESTART_AT" -eq 0 ] || [ -e "$WORK/restart-done" ]; }; then + echo "tokens: deploying and using tokens through node $TOKENS_VIA" + (cd "$HERE" && python3 tokens.py "$WORK" "$NODES" --via "$TOKENS_VIA" --json "$WORK/tokens.json" \ + $([ "$TOKENS_STRICT_API" = 1 ] && echo --strict-api)) > "$WORK/tokens.log" 2>&1 & + TOKENS_PID=$! + fi # contracts.py ended before its first calls were done: nothing would release the restart test if [ -n "$CONTRACTS_PID" ] && [ ! -e "$WORK/contracts-ready" ] && ! kill -0 "$CONTRACTS_PID" 2>/dev/null; then cat "$WORK/contracts.log" @@ -1436,6 +1454,24 @@ elif [ "$CONTRACTS" = "1" ]; then exit 1 fi +if [ -n "$TOKENS_PID" ]; then + tokens_deadline=$(( $(date +%s) + 900 )) + while kill -0 "$TOKENS_PID" 2>/dev/null && [ "$(date +%s)" -lt "$tokens_deadline" ]; do sleep 5; done + if kill -0 "$TOKENS_PID" 2>/dev/null; then + kill "$TOKENS_PID" 2>/dev/null || true + cat "$WORK/tokens.log" + echo "FAIL: tokens.py did not finish within 15 min of the target" + exit 1 + fi + tokens_status=0 + wait "$TOKENS_PID" || tokens_status=$? + cat "$WORK/tokens.log" + [ "$tokens_status" -eq 0 ] || { echo "FAIL: token checks failed"; exit 1; } +elif [ "$TOKENS" = "1" ]; then + echo "FAIL: tokens.py never started (TOKENS=1 needs CONTRACTS=1 and FUND=1)" + exit 1 +fi + if [ "$CHECKPOINT_AHEAD_AT" -gt 0 ]; then [ "${ca_done:-0}" = 1 ] || { echo "FAIL: the checkpoint-ahead test did not run (fewer than 2 checkpoints)"; exit 1; } after=$(tail -n +"$((ca_lines + 1))" "$WORK/n$CHECKPOINT_AHEAD_NODE/node.log") diff --git a/ci/testnet/tokens.py b/ci/testnet/tokens.py new file mode 100644 index 000000000..d04268f96 --- /dev/null +++ b/ci/testnet/tokens.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Token smart contracts on the private test network, through the node's API as a wallet uses it. + +Usage: tokens.py [--from-node N] [--via N] [--json OUT] [--strict-api] + +The wallet of node N (default: the last node; fund.py gave it 60'000 CS, and run.sh starts this +script once fund.py's load transfers are over, so nothing else signs with it) funds three wallets +(Alice, Bob, Carol), deploys a v1 token (ExtensionTokenStandard, +BigDecimal amounts, ci/contracts/tokens/TokenV1.java) and a v0 token (ExtensionStandard, string +amounts, TokenV0.java), then runs what token users do: transfers, approve and transferFrom, +calls that must fail, a call with the amount in the type the other standard uses, a CS payment to +the token (payable), a sale back for CS (a transaction the contract emits), burn and register. + +Checks: +- consensus: every call returns what the token's rules say, the balances read on every node + (getters through TransactionFlow with forgetNewState) agree, and every node holds the same state + of both tokens; the CS of the sale reaches the seller; +- the token API (TokensListGet, TokenInfoGet, TokenBalancesGet, TokenHoldersGet, TokenTransfersGet, + TokenTransactionsGet): what it reports against the balances the contract holds. A node built + without the token cache (every build but RelMonitor/RelWallet) answers "This node doesn't provide + such info"; that is reported. API mismatches are findings; with --strict-api they fail the run. + +Transactions go through node --via (default 1; port 9090, node i > 1 answers on 9100 + i), whose +token API is checked: with a node that was restarted, this checks that its API still reports the +results of contract calls after a quick start. +""" +import argparse +import hashlib +import json +import os +import sys +import time + +import base58 +from thriftpy2.protocol import TBinaryProtocolFactory +from thriftpy2.rpc import make_client +from thriftpy2.transport import TBufferedTransportFactory + +from contracts import CURRENCY_CS, SMART_MAX_FEE, TT_EXECUTE, deploy, smart_transaction +from fund import Client, api, balance, general, node_account, send +from fund import Account + +HERE = os.path.dirname(os.path.abspath(__file__)) +TOKENS_DIR = os.path.join(HERE, "..", "contracts", "tokens") + + +def b58(pk): + return base58.b58encode(pk).decode() + + +def v_str(s): + return general.Variant(v_string=s) + + +def v_dec(s): + return general.Variant(v_big_decimal=str(s)) + + +def v_bool(b): + return general.Variant(v_boolean=b) + + +def plain(v): + if v is None: + return None + for name in ("v_string", "v_big_decimal", "v_boolean", "v_int", "v_long", "v_double", "v_void"): + value = getattr(v, name, None) + if value is not None: + return value + return None + + +class Run: + def __init__(self, nodes, strict_api, via=1): + self.via = via + self.nodes = nodes + self.strict_api = strict_api + self.failures = 0 + self.findings = [] + self.log = [] + + def client(self, i=None): + i = self.via if i is None else i + port = 9090 if i == 1 else 9100 + i + return make_client(api.API, host="127.0.0.1", port=port, proto_factory=TBinaryProtocolFactory(), + trans_factory=TBufferedTransportFactory(), timeout=300000) + + def check(self, ok, what, kind="consensus"): + """kind: consensus (fails the run), api (a finding; fails with --strict-api), info""" + tag = "ok" if ok else ("FAILED" if kind == "consensus" or (kind == "api" and self.strict_api) else "FINDING") + print(f"[{kind}] {what}: {tag}", flush=True) + self.log.append({"kind": kind, "check": what, "ok": bool(ok)}) + if not ok: + if tag == "FAILED": + self.failures += 1 + else: + self.findings.append(f"[{kind}] {what}") + return ok + + def invoke(self, src, contract, method, params, label, amount=0): + """A contract call signed by src; returns (status code, return value, message).""" + deadline = time.time() + 120 + c = self.client() + while True: + last = c.WalletTransactionsCountGet(src.pk).lastTransactionInnerId or 0 + src.next_inner_id = int(last) + 1 + sci = api.SmartContractInvocation(method=method, params=params, usedContracts=[], forgetNewState=False, + smartContractDeploy=None, version=1) + result = c.TransactionFlow(smart_transaction(src, contract, sci, TT_EXECUTE)) + msg = result.status.message or "" + if result.status.code == 0 or ("not syncronized" not in msg and "Transaction in progress" not in msg) \ + or time.time() >= deadline: + break + time.sleep(5) + value = plain(result.smart_contract_result) + print(f" {label}: status {result.status.code} {msg.strip()[:160]!r}, returned {value!r}", flush=True) + return result.status.code, value, msg + + def read(self, i, src, contract, method, params): + sci = api.SmartContractInvocation(method=method, params=params, usedContracts=[], forgetNewState=True, + smartContractDeploy=None, version=1) + t = api.Transaction(id=0, source=src.pk, target=contract, amount=general.Amount(integral=0, fraction=0), + balance=general.Amount(integral=0, fraction=0), currency=CURRENCY_CS, signature=bytes(64), + smartContract=sci, fee=api.AmountCommission(commission=SMART_MAX_FEE), + timeCreation=int(time.time() * 1000), type=TT_EXECUTE) + r = self.client(i).TransactionFlow(t) + return plain(r.smart_contract_result) if r.status.code == 0 else None + + def read_everywhere(self, src, contract, method, params, expected, label, timeout=180): + """The getter on every node until each returns expected.""" + got = {} + for i in range(1, self.nodes + 1): + deadline = time.time() + timeout + while True: + try: + got[i] = self.read(i, src, contract, method, params) + except Exception as e: + got[i] = f"unreachable ({type(e).__name__})" + if got[i] == expected or time.time() >= deadline: + break + time.sleep(5) + return self.check(all(v == expected for v in got.values()), f"{label} = {expected!r} on every node (got {got})") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("work") + parser.add_argument("nodes", type=int) + parser.add_argument("--from-node", type=int, default=0) + parser.add_argument("--via", type=int, default=1) + parser.add_argument("--json", default="") + parser.add_argument("--strict-api", action="store_true") + args = parser.parse_args() + run = Run(args.nodes, args.strict_api, args.via) + + master = node_account(args.work, args.from_node or args.nodes) + print(f"token owner: the wallet of n{args.from_node or args.nodes}, {b58(master.pk)}", flush=True) + alice = Account(hashlib.sha256(master.pk + b"token alice").digest()) + bob = Account(hashlib.sha256(master.pk + b"token bob").digest()) + carol = Account(hashlib.sha256(master.pk + b"token carol").digest()) + funder = Client(9090 if args.via == 1 else 9100 + args.via, 300) + master.next_inner_id = None + for who in (alice, bob, carol): + ok, message = send(funder, master, who.pk, 200) + print(f"fund {b58(who.pk)[:8]}: {'ok' if ok else 'FAILED ' + str(message)}", flush=True) + deadline = time.time() + 300 + while time.time() < deadline and any(balance(funder, w.pk) < 200 for w in (alice, bob, carol)): + time.sleep(5) + + with open(os.path.join(TOKENS_DIR, "TokenV1.java")) as f: + v1_source = f.read() + with open(os.path.join(TOKENS_DIR, "TokenV0.java")) as f: + v0_source = f.read() + v1 = deploy(run.client(), master, "TokenV1", v1_source) + v0 = deploy(run.client(), master, "TokenV0", v0_source) + + # ---- v1: BigDecimal amounts --------------------------------------------------------------- + print("TokenV1 calls", flush=True) + s, r, _ = run.invoke(master, v1, "transfer", [v_str(b58(alice.pk)), v_dec("1000")], "master -> alice 1000") + run.check(s == 0 and r is True, "v1 transfer with a BigDecimal amount") + s, r, m = run.invoke(master, v1, "transfer", [v_str(b58(bob.pk)), v_str("5")], "master -> bob \"5\" (string amount)") + run.check(s == 0 and r is True, "v1 transfer with the amount as a string (the only form the API's token cache " + "recognises as a transfer)", kind="info") + s, r, _ = run.invoke(alice, v1, "transfer", [v_str(b58(bob.pk)), v_dec("100.5")], "alice -> bob 100.5") + run.check(s == 0 and r is True, "v1 transfer by a holder") + s, r, _ = run.invoke(alice, v1, "transfer", [v_str(b58(bob.pk)), v_dec("999999")], "alice -> bob 999999") + run.check(r is not True, "v1 transfer above the balance fails") + s, r, _ = run.invoke(master, v1, "approve", [v_str(b58(bob.pk)), v_dec("50")], "master approves bob 50") + s, r, _ = run.invoke(bob, v1, "transferFrom", [v_str(b58(master.pk)), v_str(b58(carol.pk)), v_dec("20")], + "bob moves 20 master -> carol") + run.check(s == 0 and r is True, "v1 transferFrom within the allowance") + s, r, _ = run.invoke(carol, v1, "register", [], "carol registers") + # a CS payment to the token: the node calls payable(BigDecimal, byte[]) + master.next_inner_id = None + alice.next_inner_id = None + ok, message = send(funder, alice, v1, 10) + print(f" alice pays 10 CS to TokenV1: {'ok' if ok else 'FAILED ' + str(message)}", flush=True) + time.sleep(20) + s, r, _ = run.invoke(bob, v1, "sell", [v_dec("2")], "bob sells 2 tokens for CS") + run.check(s == 0 and r is True, "v1 sell (the contract emits a CS transaction)") + s, r, _ = run.invoke(master, v1, "burn", [v_dec("1000")], "master burns 1000") + + expected_v1 = {b58(alice.pk): "909.500", b58(bob.pk): "98.500", b58(carol.pk): "20.000"} + for who, value in expected_v1.items(): + run.read_everywhere(master, v1, "balanceOf", [v_str(who)], value, f"TokenV1 balanceOf {who[:8]}") + run.read_everywhere(master, v1, "totalSupply", [], "9999000.000", "TokenV1 totalSupply") + + # ---- v0: string amounts -------------------------------------------------------------------- + print("TokenV0 calls", flush=True) + s, r, _ = run.invoke(master, v0, "transfer", [v_str(b58(alice.pk)), v_str("10.5")], "master -> alice \"10.5\"") + run.check(s == 0 and r is True, "v0 transfer with a string amount") + s, r, _ = run.invoke(master, v0, "transfer", [v_str(b58(bob.pk)), v_dec("1")], "master -> bob 1 (BigDecimal amount)") + run.check(s == 0 and r is True, "v0 transfer with a BigDecimal amount", kind="info") + s, r, _ = run.invoke(alice, v0, "approve", [v_str(b58(bob.pk)), v_str("5")], "alice approves bob 5") + s, r, _ = run.invoke(bob, v0, "transferFrom", [v_str(b58(alice.pk)), v_str(b58(bob.pk)), v_str("5")], + "bob moves 5 alice -> bob") + run.check(s == 0 and r is True, "v0 transferFrom") + run.read_everywhere(master, v0, "balanceOf", [v_str(b58(alice.pk))], "5.50", "TokenV0 balanceOf alice") + run.read_everywhere(master, v0, "balanceOf", [v_str(b58(bob.pk))], "5.00", "TokenV0 balanceOf bob") + + # ---- CS of the sale ------------------------------------------------------------------------ + bob_cs = balance(funder, bob.pk) + run.check(bob_cs > 200, f"the 2 CS of the sale reached Bob (balance {bob_cs})") + + # ---- same state on every node ---------------------------------------------------------------- + time.sleep(30) + for name, contract in (("TokenV1", v1), ("TokenV0", v0)): + states = {} + for i in range(1, args.nodes + 1): + try: + got = run.client(i).SmartContractGet(contract) + states[i] = hashlib.sha256(got.smartContract.objectState).hexdigest()[:16] if got.status.code == 0 else "error" + except Exception as e: + states[i] = f"unreachable ({type(e).__name__})" + run.check(len(set(states.values())) == 1, f"{name} state is the same on every node ({states})") + + # ---- the token API ----------------------------------------------------------------------------- + print(f"token API on node {args.via}", flush=True) + c = run.client() + lst = c.TokensListGet(0, 100, 0, False, api.TokenFilters(name="", code="", tokenStandard=0)) + if lst.status.code != 0: + run.check(False, f"TokensListGet answers ({lst.status.message!r}): the token API needs a node built with the " + f"token cache", kind="api") + else: + found = {b58(t.address): t for t in (lst.tokens or [])} + for name, contract, std in (("TokenV1", v1, 4), ("TokenV0", v0, 2)): + t = found.get(b58(contract)) + run.check(t is not None, f"TokensListGet lists {name}", kind="api") + if t is not None: + run.check(t.tokenStandard == std, f"{name} token standard {std} (got {t.tokenStandard})", kind="api") + run.check(t.code and t.name, f"{name} name and symbol ({t.name!r}, {t.code!r})", kind="api") + for who, label in ((alice, "alice"), (bob, "bob"), (carol, "carol")): + tb = c.TokenBalancesGet(who.pk) + got = {b58(b.token): b.balance for b in (tb.balances or [])} + print(f" TokenBalancesGet {label}: {got}", flush=True) + want = expected_v1.get(b58(who.pk)) + have = got.get(b58(v1)) + run.check(have is not None and want is not None and float(have) == float(want), + f"TokenBalancesGet {label}: TokenV1 balance {want} (got {have})", kind="api") + info = c.TokenInfoGet(v1) + if info.status.code == 0: + t = info.token + print(f" TokenInfoGet TokenV1: holders {t.holdersCount} transfers {t.transfersCount} " + f"transactions {t.transactionsCount} supply {t.totalSupply}", flush=True) + run.check(t.holdersCount >= 4, f"TokenV1 holders count >= 4 (got {t.holdersCount})", kind="api") + run.check(t.transfersCount >= 3, f"TokenV1 transfers count >= 3 (got {t.transfersCount})", kind="api") + run.check(t.totalSupply and float(t.totalSupply) == 9999000.0, f"TokenV1 total supply (got {t.totalSupply!r})", + kind="api") + else: + run.check(False, f"TokenInfoGet answers ({info.status.message!r})", kind="api") + tr = c.TokenTransfersGet(v1, 0, 100) + print(f" TokenTransfersGet TokenV1: status {tr.status.code}, count {tr.count}, " + f"listed {len(tr.transfers or [])}", flush=True) + run.check(tr.status.code == 0 and len(tr.transfers or []) >= 3, + f"TokenTransfersGet lists the v1 transfers (got {len(tr.transfers or [])})", kind="api") + holders = c.TokenHoldersGet(v1, 0, 100, 0, True) + print(f" TokenHoldersGet TokenV1: status {holders.status.code} " + f"{[(b58(h.holder)[:8], h.balance) for h in (holders.holders or [])]}", flush=True) + run.check(holders.status.code == 0 and len(holders.holders or []) >= 4, "TokenHoldersGet lists the v1 holders", + kind="api") + + print(f"\n{run.failures} failures, {len(run.findings)} findings", flush=True) + for f in run.findings: + print(" " + f) + if args.json: + with open(args.json, "w") as f: + json.dump(run.log, f, indent=1) + sys.exit(1 if run.failures else 0) + + +if __name__ == "__main__": + main() diff --git a/docs/CHANGES.md b/docs/CHANGES.md index a24951ddb..2831a0139 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -42,6 +42,7 @@ lines under the new release. | #119 | ci: the release checks the Windows and macOS packages on mainnet before publishing them (a node of each system restores the published snapshot, syncs to the head, logs the same state digests as Linux and stops cleanly), and the same check runs weekly on the latest published release | | #120 | ci: a private network of 7 nodes (with the restart of one at block 300) runs on macOS and on Windows every night and on demand (`testnet-platforms.yml`): the nodes reach the same state digests as on Linux and a stopped node quick-starts again; Linux-only scenarios (network faults, slow nodes, full disks) stay on Linux | | #126 | api: after a quick start at the last stored block, contract calls through the API returned "Transaction in progress" and never their result; the node now marks its stored blocks as read when it runs | +| #127 | ci: token tests: `ci/contracts/executor_harness.py` compares contract executors on token contracts without a node, and `TOKENS=1` runs `ci/testnet/tokens.py` (v1 and v0 tokens, balances and states on every node, the token API; `TOKENS_VIA` through another node) on the private network | ## community.14 — 2026-10-27