Esempio n. 1
0
    def verifyRecreation() -> None:
        template: Dict[str,
                       Any] = rpc.call("merit", "getBlockTemplate",
                                       [key.toPublicKey().serialize().hex()])
        if bytes.fromhex(
                template["header"])[36:68] != BlockHeader.createContents(
                    [VerificationPacket(data.hash, [1])]):
            raise TestError(
                "New Block template doesn't have a properly recreated packet.")

        #Mining it further verifies the internal state.
        header: bytes = bytes.fromhex(template["header"])
        proof: int = 0
        sig: bytes
        while True:
            initial: bytes = RandomX(header +
                                     proof.to_bytes(4, byteorder="little"))
            sig = key.sign(initial).serialize()
            final: bytes = RandomX(initial + sig)
            if (int.from_bytes(final, "little") *
                    template["difficulty"]) < int.from_bytes(
                        bytes.fromhex("FF" * 32), "little"):
                break
            proof += 1

        rpc.call("merit", "publishBlock", [
            template["id"],
            (header + proof.to_bytes(4, byteorder="little") + sig).hex()
        ])

        raise SuccessError(
            "Stop Liver from trying to verify the vector chain which doesn't have this Block."
        )
Esempio n. 2
0
 def verifyTemplate() -> None:
     if bytes.fromhex(
             rpc.call("merit", "getBlockTemplate",
                      {"miner": blsPubKey
                       })["header"])[36:68] != BlockHeader.createContents(
                           [VerificationPacket(sends[2].hash, [1])]):
         raise TestError(
             "Meros didn't add a SignedVerification to the Block Template.")
Esempio n. 3
0
  def sendDataAndVerifications() -> None:
    if rpc.meros.liveTransaction(data) != rpc.meros.live.recv():
      raise TestError("Meros didn't rebroadcast a Transaction we sent it.")
    for sv in svs:
      if rpc.meros.signedElement(sv) != rpc.meros.live.recv():
        raise TestError("Meros didn't rebroadcast a SignedVerification we sent it.")

    #As we don't have a quality RPC route for this, we need to use getTemplate.
    if bytes.fromhex(
      rpc.call("merit", "getBlockTemplate", [key.toPublicKey().serialize().hex()])["header"]
    )[36 : 68] != BlockHeader.createContents([VerificationPacket(data.hash, [0, 1])]):
      raise TestError("New Block template doesn't have a properly created packet.")
Esempio n. 4
0
competingData: Data = Data(bytes.fromhex("11" * 32), bytes(2))
transactions.add(competingData)

#Verify the Datas.
verif: SignedVerification = SignedVerification(data.hash)
verif.sign(0, blsPrivKey)

competingVerif: SignedVerification = SignedVerification(competingData.hash)
competingVerif.sign(0, blsPrivKey)

#Create a MeritRemoval out of the conflicting Verifications.
mr: SignedMeritRemoval = SignedMeritRemoval(verif, competingVerif)

#Generate a Block containing the MeritRemoval.
block = Block(
    BlockHeader(0, blockchain.last(), BlockHeader.createContents([], [mr]), 1,
                bytes(4), BlockHeader.createSketchCheck(bytes(4), []), 0,
                blockchain.blocks[-1].header.time + 1200),
    BlockBody([], [mr], mr.signature))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Invalid Competing Block " + str(len(blockchain.blocks)) + ".")

result: Dict[str, Any] = {
    "blockchain": blockchain.toJSON(),
    "transactions": transactions.toJSON(),
    "removal": mr.toSignedJSON()
}
Esempio n. 5
0
#Create a Data and verify it by both parties.
data: Data = Data(bytes(32), edPubKey.to_bytes())
data.sign(edPrivKey)
data.beat(spamFilter)
transactions.add(data)

verifs: List[SignedVerification] = [
    SignedVerification(data.hash),
    SignedVerification(data.hash)
]
verifs[0].sign(0, blsPrivKeys[0])
verifs[1].sign(1, blsPrivKeys[1])
packets: List[VerificationPacket] = [VerificationPacket(data.hash, [0])]

block = Block(
    BlockHeader(0, blockchain.last(), BlockHeader.createContents(packets), 1,
                bytes(4), BlockHeader.createSketchCheck(bytes(4), packets), 1,
                blockchain.blocks[-1].header.time + 1200),
    BlockBody(packets, [], verifs[0].signature))
for _ in range(6):
    block.mine(blsPrivKeys[1], blockchain.difficulty())
    blockchain.add(block)
    print("Generated Hundred Forty Two Block " + str(len(blockchain.blocks)) +
          ".")

    #Create the next Block.
    block = Block(
        BlockHeader(0, blockchain.last(), bytes(32), 1, bytes(4), bytes(32), 1,
                    blockchain.blocks[-1].header.time + 1200), BlockBody())

#Save the appended data (3 Blocks and 12 Sends).
Esempio n. 6
0
      str(len(blockchain.blocks)) + ".")

#Create conflicting Data Difficulties.
dataDiffs: List[SignedDataDifficulty] = [
    SignedDataDifficulty(3, 0),
    SignedDataDifficulty(4, 0)
]
dataDiffs[0].sign(0, blsPrivKey)
dataDiffs[1].sign(0, blsPrivKey)

#Create a MeritRemoval out of the conflicting Data Difficulties.
mr: SignedMeritRemoval = SignedMeritRemoval(dataDiffs[0], dataDiffs[1])

#Generate a Block containing the MeritRemoval.
block = Block(
    BlockHeader(0, blockchain.last(), BlockHeader.createContents([], [mr]), 1,
                bytes(4), bytes(32), 0,
                blockchain.blocks[-1].header.time + 1200),
    BlockBody([], [mr], mr.signature))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Hundred Twenty Three Swap Block " +
      str(len(blockchain.blocks)) + ".")

#Create a MeritRemoval with the Elements swapped.
swapped: SignedMeritRemoval = SignedMeritRemoval(dataDiffs[1], dataDiffs[0])

#Generate a Block containing the swapped MeritRemoval.
Esempio n. 7
0
blocks: List[Dict[str, Any]] = json.loads(bbFile.read())
blockchain: Blockchain = Blockchain.fromJSON(blocks)
bbFile.close()

#BLS Keys.
blsPrivKey: PrivateKey = PrivateKey(blake2b(b'\0', digest_size=32).digest())
blsPubKey: PublicKey = blsPrivKey.toPublicKey()

#Create a SendDifficulty.
sendDiff: SignedSendDifficulty = SignedSendDifficulty(5, 0)
sendDiff.sign(0, blsPrivKey)

#Generate a Block containing the SendDifficulty.
block = Block(
    BlockHeader(0, blockchain.last(),
                BlockHeader.createContents([], [sendDiff]), 1, bytes(4),
                bytes(32), 0, blockchain.blocks[-1].header.time + 1200),
    BlockBody([], [sendDiff], sendDiff.signature))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated SendDifficulty Block " + str(len(blockchain.blocks)) + ".")

#Mine 24 more Blocks until there's a vote.
for _ in range(24):
    block = Block(
        BlockHeader(0, blockchain.last(), bytes(32), 1, bytes(4), bytes(32), 0,
                    blockchain.blocks[-1].header.time + 1200), BlockBody())
    #Mine it.
Esempio n. 8
0
def getBlockTemplateTest(rpc: RPC) -> None:
    edPrivKey: Ristretto.SigningKey = Ristretto.SigningKey(b'\0' * 32)
    edPubKey: bytes = edPrivKey.get_verifying_key()
    blockchain: Blockchain = Blockchain()

    #Get multiple templates to verify they share an ID if they're requested within the same second.
    templates: List[Dict[str, Any]] = []
    startTime: float = nextSecond()
    for k in range(5):
        templates.append(
            rpc.call("merit", "getBlockTemplate", {"miner": getMiner(k)},
                     False))
    if int(startTime) != int(time.time()):
        #Testing https://github.com/MerosCrypto/Meros/issues/278 has a much more forgiving timer of < 1 second each.
        #That said, this test was written on the fair assumption of all the above taking place in a single second.
        raise Exception(
            "getBlockTemplate is incredibly slow, to the point an empty Block template takes > 0.2 seconds to grab, invalidating this test."
        )

    for k, template in zip(range(5), templates):
        if template["id"] != int(startTime):
            raise TestError("Template ID isn't the time.")

        #Also check general accuracy.
        if bytes.fromhex(template["key"]) != blockchain.genesis:
            raise TestError("Template has the wrong RandomX key.")

        bytesHeader: bytes = bytes.fromhex(template["header"])
        serializedHeader: bytes = BlockHeader(
            0, blockchain.blocks[0].header.hash, bytes(32), 0, bytes(4),
            bytes(32),
            PrivateKey(k).toPublicKey().serialize(),
            int(startTime)).serialize()[:-52]
        #Skip over the randomized sketch salt.
        if (bytesHeader[:72] + bytesHeader[76:]) != (serializedHeader[:72] +
                                                     serializedHeader[76:]):
            raise TestError("Template has an invalid header.")
        #Difficulty modified as this is a new miner.
        if template["difficulty"] != (blockchain.difficulty() * 11 // 10):
            raise TestError("Template's difficulty is wrong.")

    currTime: int = int(nextSecond())
    template: Dict[str, Any] = rpc.call("merit", "getBlockTemplate",
                                        {"miner": getMiner(0)}, False)
    if template["id"] != currTime:
        raise TestError("Template ID wasn't advanced with the time.")

    #Override the ID to enable easy comparison against a historical template.
    template["id"] = int(startTime)

    if int.from_bytes(bytes.fromhex(template["header"])[-4:],
                      "little") != currTime:
        raise TestError("The header has the wrong time.")
    template["header"] = (
        bytes.fromhex(template["header"])[:72] +
        #Use the header we'll compare to's salt.
        bytes.fromhex(templates[0]["header"])[72:76] +
        bytes.fromhex(template["header"])[76:-4] +
        #Also use its time.
        int(startTime).to_bytes(4, "little")).hex().upper()

    if template != templates[0]:
        raise TestError(
            "Template, minus the time difference, doesn't match the originally provided template."
        )

    #Test that the templates are deleted whenever a new Block appears.
    #This is done by checking the error given when we use an old template.
    with open("e2e/Vectors/Merit/BlankBlocks.json", "r") as file:
        block: Block = Block.fromJSON(json.loads(file.read())[0])
        blockchain.add(block)
        rpc.meros.liveConnect(blockchain.blocks[0].header.hash)
        rpc.meros.syncConnect(blockchain.blocks[0].header.hash)
        rpc.meros.liveBlockHeader(block.header)
        rpc.meros.rawBlockBody(block, 0)
        time.sleep(1)
    #Sanity check.
    if rpc.call("merit", "getHeight", auth=False) != 2:
        raise Exception("Didn't successfully send Meros the Block.")

    #Get a new template so Meros realizes the template situation has changed.
    rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)}, False)

    try:
        rpc.call("merit", "publishBlock", {
            "id": int(startTime),
            "header": ""
        }, False)
        raise Exception("")
    except Exception as e:
        if str(e) != "-2 Invalid ID.":
            raise TestError("Meros didn't delete old template IDs.")

    #Test VerificationPacket inclusion.
    data: Data = Data(bytes(32), edPubKey)
    data.sign(edPrivKey)
    data.beat(SpamFilter(5))
    verif: SignedVerification = SignedVerification(data.hash)
    verif.sign(0, PrivateKey(0))
    packet = VerificationPacket(data.hash, [0])

    rpc.meros.liveTransaction(data)
    rpc.meros.signedElement(verif)
    time.sleep(1)
    if bytes.fromhex(
            rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                     False)["header"])[36:68] != BlockHeader.createContents(
                         [packet]):
        raise TestError(
            "Meros didn't include the Verification in its new template.")

    #Test Element inclusion.
    sendDiff: SignedSendDifficulty = SignedSendDifficulty(0, 0)
    sendDiff.sign(0, PrivateKey(0))
    rpc.meros.signedElement(sendDiff)
    time.sleep(1)
    if bytes.fromhex(
            rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                     False)["header"])[36:68] != BlockHeader.createContents(
                         [packet], [sendDiff]):
        raise TestError(
            "Meros didn't include the Element in its new template.")

    #The 88 test checks for the non-inclusion of Verifications with unmentioned predecessors.
    #Test for non-inclusion of Elements with unmentioned predecessors.
    sendDiffChild: SignedSendDifficulty = SignedSendDifficulty(0, 2)
    sendDiffChild.sign(0, PrivateKey(0))
    rpc.meros.signedElement(sendDiffChild)
    time.sleep(1)
    if bytes.fromhex(
            rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                     False)["header"])[36:68] != BlockHeader.createContents(
                         [packet], [sendDiff]):
        raise TestError(
            "Meros did include an Element with an unmentioned parent in its new template."
        )

    #If we send a block with a time in the future, yet within FTL (of course), make sure Meros can still generate a template.
    #Naively using the current time will create a negative clock, which isn't allowed.
    #Start by closing the sockets to give us time to work.
    rpc.meros.live.connection.close()
    rpc.meros.sync.connection.close()
    #Sleep to reset the connection state.
    time.sleep(35)

    #Create and mine the Block.
    header: BlockHeader = BlockHeader(
        0,
        blockchain.blocks[-1].header.hash,
        bytes(32),
        0,
        bytes(4),
        bytes(32),
        PrivateKey(0).toPublicKey().serialize(),
        0,
    )
    miningStart: int = 0
    #If this block takes longer than 10 seconds to mine, try another.
    #Low future time (20 seconds) is chosen due to feasibility + supporting lowering the FTL in the future.
    while time.time() > miningStart + 10:
        miningStart = int(time.time())
        header = BlockHeader(
            0,
            blockchain.blocks[-1].header.hash,
            bytes(32),
            0,
            bytes(4),
            bytes(32),
            #Mod by something is due to a 2-byte limit (IIRC -- Kayaba).
            #100 is just clean. +11 ensures an offset from the above, which really shouldn't be necessary.
            #If we did need one, +1 should work, as we only ever work with PrivateKey(0) on the blockchain.
            PrivateKey((miningStart % 100) + 10).toPublicKey().serialize(),
            int(time.time()) + 20,
        )
        header.mine(PrivateKey((miningStart % 100) + 10),
                    blockchain.difficulty() * 11 // 10)
    blockchain.add(Block(header, BlockBody()))

    #Send it and verify it.
    rpc.meros.liveConnect(blockchain.blocks[0].header.hash)
    rpc.meros.syncConnect(blockchain.blocks[0].header.hash)
    rpc.meros.liveBlockHeader(header)
    rpc.meros.rawBlockBody(Block(header, BlockBody()), 0)
    rpc.meros.live.connection.close()
    rpc.meros.sync.connection.close()
    time.sleep(1)

    #Ensure a stable template ID.
    currTime = int(nextSecond())
    template = rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                        False)
    if template["id"] != currTime:
        raise TestError(
            "Template ID isn't the time when the previous Block is in the future."
        )
    if int.from_bytes(bytes.fromhex(template["header"])[-4:],
                      "little") != (header.time + 1):
        raise TestError(
            "Meros didn't handle generating a template off a Block in the future properly."
        )

    #Verify a Block with three Elements from a holder, where two form a Merit Removal.
    #Only the two which cause a MeritRemoval should be included.
    #Mine a Block to a new miner and clear the current template with it (might as well).
    #Also allows us to test template clearing.
    template: Dict[str, Any] = rpc.call("merit", "getBlockTemplate",
                                        {"miner": getMiner(1)}, False)
    #Mine the Block.
    proof: int = -1
    tempHash: bytes = bytes()
    tempSignature: bytes = bytes()
    while ((proof == -1)
           or ((int.from_bytes(tempHash, "little") *
                (blockchain.difficulty() * 11 // 10)) > int.from_bytes(
                    bytes.fromhex("FF" * 32), "little"))):
        proof += 1
        tempHash = RandomX(
            bytes.fromhex(template["header"]) + proof.to_bytes(4, "little"))
        tempSignature = PrivateKey(1).sign(tempHash).serialize()
        tempHash = RandomX(tempHash + tempSignature)
    rpc.call(
        "merit", "publishBlock", {
            "id":
            template["id"],
            "header":
            template["header"] + proof.to_bytes(4, "little").hex() +
            tempSignature.hex()
        })
    time.sleep(1)

    #Verify the template was cleared.
    currTime = int(nextSecond())
    bytesHeader: bytes = bytes.fromhex(
        rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                 False)["header"])
    serializedHeader: bytes = BlockHeader(
        0,
        tempHash,
        bytes(32),
        0,
        bytes(4),
        bytes(32),
        0,
        #Ensures that the previous time manipulation doesn't come back to haunt us.
        max(currTime, blockchain.blocks[-1].header.time + 1)).serialize()[:-52]
    #Skip over the randomized sketch salt and time (which we don't currently have easy access to).
    if (bytesHeader[:72] + bytesHeader[76:-4]) != (serializedHeader[:72] +
                                                   serializedHeader[76:-4]):
        raise TestError("Template wasn't cleared.")

    #Sleep so we can reconnect.
    time.sleep(35)
    rpc.meros.liveConnect(blockchain.blocks[0].header.hash)

    #Finally create the Elements.
    dataDiff: SignedDataDifficulty = SignedDataDifficulty(1, 0)
    dataDiff.sign(2, PrivateKey(1))
    rpc.meros.signedElement(dataDiff)
    sendDiffs: List[SignedSendDifficulty] = [
        SignedSendDifficulty(1, 1),
        SignedSendDifficulty(2, 1)
    ]
    for sd in sendDiffs:
        sd.sign(2, PrivateKey(1))
        rpc.meros.signedElement(sd)
    time.sleep(1)

    #`elem for elem` is used below due to Pyright not handling inheritance properly when nested.
    #pylint: disable=unnecessary-comprehension
    if bytes.fromhex(
            rpc.call("merit", "getBlockTemplate", {"miner": getMiner(0)},
                     False)["header"])[36:68] != BlockHeader.createContents(
                         [], [elem for elem in sendDiffs[::-1]]):
        raise TestError(
            "Meros didn't include just the malicious Elements in its new template."
        )
Esempio n. 9
0
)
send.sign(edPrivKey)
send.beat(sendFilter)
transactions.add(send)

#Create a Verification/VerificationPacket for the Send.
sv: SignedVerification = SignedVerification(send.hash)
sv.sign(0, blsPrivKey)
packet: VerificationPacket = VerificationPacket(send.hash, [0])

#Add a Block verifying it.
block: Block = Block(
  BlockHeader(
    0,
    blockchain.last(),
    BlockHeader.createContents([packet]),
    1,
    bytes(4),
    BlockHeader.createSketchCheck(bytes(4), [packet]),
    0,
    blockchain.blocks[-1].header.time + 1200
  ),
  BlockBody([packet], [], sv.signature)
)

#Mine the Block.
block.mine(blsPrivKey, blockchain.difficulty())

#Add the Block.
blockchain.add(block)
print("Generated Same Input Block " + str(len(blockchain.blocks) - 1) + ".")
Esempio n. 10
0
    toAggregate = []

    for h in order[0]:
        for s in order[0][h]:
            if s not in packets:
                packets[s] = VerificationPacket(sends[s].hash, [])
            packets[s].holders.append(h)

            verif: SignedVerification = SignedVerification(sends[s].hash)
            verif.sign(h, blsPrivKeys[h])
            toAggregate.append(verif.signature)

    block: Block = Block(
        BlockHeader(
            0, blockchain.last(),
            BlockHeader.createContents(list(packets.values())), 1, bytes(4),
            BlockHeader.createSketchCheck(bytes(4), list(packets.values())),
            order[1], blockchain.blocks[-1].header.time + 1200),
        BlockBody(list(packets.values()), [],
                  Signature.aggregate(toAggregate)))

    miner: Union[bytes, int] = order[1]
    if isinstance(miner, bytes):
        for k in range(len(blsPubKeys)):
            if miner == blsPubKeys[k].serialize():
                block.mine(blsPrivKeys[k], blockchain.difficulty())
                break
    else:
        block.mine(blsPrivKeys[miner], blockchain.difficulty())

    blockchain.add(block)
Esempio n. 11
0
    for v in range(2):
        verifs[-1][v].sign(v, blsPrivKeys[v])

#Create the packets.
packets: List[SignedVerificationPacket] = []
for packet in verifs:
    packets.append(
        SignedVerificationPacket(
            packet[0].hash, [0, 1],
            Signature.aggregate([packet[0].signature, packet[1].signature])))

#Create Blocks containing these packets.
for packet in packets:
    block = Block(
        BlockHeader(0, merit.blockchain.last(),
                    BlockHeader.createContents([packet]), 1, bytes(4),
                    BlockHeader.createSketchCheck(bytes(4), [packet]), 1,
                    merit.blockchain.blocks[-1].header.time + 1200),
        BlockBody([packet], [], packet.signature))
    block.mine(blsPrivKeys[1], merit.blockchain.difficulty())
    merit.add(block)
    print("Generated Aggregated Claim Block " +
          str(len(merit.blockchain.blocks) - 1) + ".")

#Generate another 5 Blocks to close the Epochs.
#Next block should have the packet.
for _ in range(5):
    block = Block(
        BlockHeader(0, merit.blockchain.last(), bytes(32), 1, bytes(4),
                    bytes(32),
                    0, merit.blockchain.blocks[-1].header.time + 1200),
Esempio n. 12
0
print("Generated Hundred Twenty Three Partial Block " + str(len(blockchain.blocks)) + ".")

#Create conflicting Data Difficulties.
dataDiffs: List[SignedDataDifficulty] = [
  SignedDataDifficulty(3, 0),
  SignedDataDifficulty(4, 0)
]
dataDiffs[0].sign(0, blsPrivKey)
dataDiffs[1].sign(0, blsPrivKey)

#Generate a Block containing the first Data Difficulty.
block = Block(
  BlockHeader(
    0,
    blockchain.last(),
    BlockHeader.createContents([], [dataDiffs[0]]),
    1,
    bytes(4),
    bytes(32),
    0,
    blockchain.blocks[-1].header.time + 1200
  ),
  BlockBody([], [dataDiffs[0]], dataDiffs[0].signature)
)
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Hundred Twenty Three Partial Block " + str(len(blockchain.blocks)) + ".")
Esempio n. 13
0
                b'\3', digest_size=32).digest()).toPublicKey().serialize(),
            PrivateKey(blake2b(
                b'\4', digest_size=32).digest()).toPublicKey().serialize()
        ],
        Signature.aggregate([
            blsPrivKey.sign(verifs[2].signatureSerialize()),
            PrivateKey(blake2b(b'\3', digest_size=32).digest()).sign(
                verifs[2].signatureSerialize()),
            PrivateKey(blake2b(b'\4', digest_size=32).digest()).sign(
                verifs[2].signatureSerialize())
        ])), 0)

#Generate a Block containing the modified MeritRemoval.
block = Block(
    BlockHeader(0, blockchain.last(),
                BlockHeader.createContents([], [packeted]), 1, bytes(4),
                bytes(32), 0, blockchain.blocks[-1].header.time + 1200),
    BlockBody([], [packeted], packeted.signature))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Hundred Thirty Five Block " + str(len(blockchain.blocks)) +
      ".")

result: Dict[str, Any] = {
    "blockchain": blockchain.toJSON(),
    "datas": [datas[0].toJSON(), datas[1].toJSON(), datas[2].toJSON()],
    "removal": mr.toSignedJSON()
}
Esempio n. 14
0
    blsPubKey.serialize(),
    blockchain.blocks[-1].header.time + 1200
  ),
  BlockBody()
)
blank.mine(blsPrivKey, blockchain.difficulty())
blockchain.add(blank)

#Generate a Block which has a VP with no holders.
vp: VerificationPacket = VerificationPacket(b'z' * 32, [])
blocks.append(
  Block(
    BlockHeader(
      0,
      blockchain.last(),
      BlockHeader.createContents([vp]),
      1,
      bytes(4),
      BlockHeader.createSketchCheck(bytes(4), [vp]),
      0,
      blockchain.blocks[-1].header.time + 1200
    ),
    BlockBody([vp], [], blsPrivKey.sign(b''))
  )
)
blocks[-1].mine(blsPrivKey, blockchain.difficulty())

#Generate a Block which has a MR VP with no holders.
mr: MeritRemoval = MeritRemoval(
  MeritRemovalVerificationPacket(b'z' * 32, []),
  MeritRemovalVerificationPacket(b'z' * 32, []),
Esempio n. 15
0
      PrivateKey(blake2b(b'\1', digest_size=32).digest()).toPublicKey().serialize()
    ],
    PrivateKey(blake2b(b'\1', digest_size=32).digest()).sign(verifs[1].signatureSerialize())
  )
]

#Create a MeritRemoval out of the conflicting Verifications.
e1MR: SignedMeritRemoval = SignedMeritRemoval(verifs[1], packets[0], 0)
e2MR: SignedMeritRemoval = SignedMeritRemoval(packets[1], verifs[2], 0)

#Generate a Block containing the MeritRemoval for each chain.
block = Block(
  BlockHeader(
    0,
    e1Chain.last(),
    BlockHeader.createContents([], [e1MR]),
    1,
    bytes(4),
    bytes(32),
    0,
    e1Chain.blocks[-1].header.time + 1200
  ),
  BlockBody([], [e1MR], e1MR.signature)
)
block.mine(blsPrivKey, e1Chain.difficulty())
e1Chain.add(block)
print("Generated Hundred Twenty Three Packet Block 1 " + str(len(e1Chain.blocks)) + ".")

block = Block(
  BlockHeader(
    0,
Esempio n. 16
0
    blsPubKey.serialize(),
    blockchain.blocks[-1].header.time + 1200
  ),
  BlockBody()
)
blank.mine(blsPrivKey, blockchain.difficulty())
blockchain.add(blank)

#Generate a Block which has a VP with no holders.
vp: VerificationPacket = VerificationPacket(b'z' * 32, [])
blocks.append(
  Block(
    BlockHeader(
      0,
      blockchain.last(),
      BlockHeader.createContents([vp]),
      1,
      bytes(4),
      BlockHeader.createSketchCheck(bytes(4), [vp]),
      0,
      blockchain.blocks[-1].header.time + 1200
    ),
    BlockBody([vp], [], blsPrivKey.sign(b''))
  )
)
blocks[-1].mine(blsPrivKey, blockchain.difficulty())

with open("e2e/Vectors/Consensus/TwoHundredFour.json", "w") as vectors:
  vectors.write(json.dumps({
    "blank": blank.toJSON(),
    "blocks": [block.toJSON() for block in blocks]
Esempio n. 17
0
edPubKey: ed25519.VerifyingKey = edPrivKey.get_verifying_key()

#BLS Private Key.
blsPrivKey: PrivateKey = PrivateKey(blake2b(b'\0', digest_size=32).digest())

#Create a Data for the VerificationPacket.
data: Data = Data(bytes(32), edPubKey.to_bytes())
data.sign(edPrivKey)
data.beat(dataFilter)
transactions.add(data)

#Generate the VerificationPacket Block.
block = Block(
    BlockHeader(
        0, blockchain.last(),
        BlockHeader.createContents([VerificationPacket(data.hash, [1])]), 1,
        bytes(4),
        BlockHeader.createSketchCheck(bytes(4),
                                      [VerificationPacket(data.hash, [1])]),
        blsPrivKey.toPublicKey().serialize(),
        blockchain.blocks[-1].header.time + 1200),
    BlockBody([VerificationPacket(data.hash, [1])], [], blsPrivKey.sign(b"")))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it to the vectors.
blocks.append(block.toJSON())
print("Generated Hundred Six Block Elements VerificationPacket Block.")

#Generate the SendDifficulty Block.
elements: List[Element] = []
Esempio n. 18
0
  data.sign(edPrivKey)
  data.beat(dataFilter)
  transactions.add(data)

#Verify them in unique Blocks.
packet: List[VerificationPacket]
for data in datas:
  verif: SignedVerification = SignedVerification(data.hash)
  verif.sign(0, blsPrivKey)
  packet = [VerificationPacket(data.hash, [0])]

  block = Block(
    BlockHeader(
      0,
      merit.blockchain.last(),
      BlockHeader.createContents(packet),
      1,
      bytes(4),
      BlockHeader.createSketchCheck(bytes(4), packet),
      0,
      merit.blockchain.blocks[-1].header.time + 1200
    ),
    BlockBody(packet, [], verif.signature)
  )
  block.mine(blsPrivKey, merit.blockchain.difficulty())
  merit.add(block)

#Generate another 5 Blocks to close the Epochs.
for _ in range(5):
  block = Block(
    BlockHeader(
Esempio n. 19
0
#Create the Data.
data: Data = Data(bytes(32), edPubKey.to_bytes())
data.sign(edPrivKey)
data.beat(dataFilter)
transactions.add(data)

#Verify it.
verif: SignedVerification = SignedVerification(data.hash)
verif.sign(0, blsPrivKey)

#Generate another 6 Blocks.
#Next block should have a packet.
block: Block = Block(
    BlockHeader(
        0, merit.blockchain.last(),
        BlockHeader.createContents([VerificationPacket(verif.hash, [0])]), 1,
        bytes(4),
        BlockHeader.createSketchCheck(bytes(4),
                                      [VerificationPacket(verif.hash, [0])]),
        0, merit.blockchain.blocks[-1].header.time + 1200),
    BlockBody([VerificationPacket(verif.hash, [0])], [], verif.signature))
for _ in range(6):
    #Mine it.
    block.mine(blsPrivKey, merit.blockchain.difficulty())

    #Add it.
    merit.add(block)
    print("Generated Claimed Mint Block " +
          str(len(merit.blockchain.blocks) - 1) + ".")

    #Create the next Block.
Esempio n. 20
0
#Create Verifications for all 3.
verifs: List[SignedVerification] = []
packets: List[VerificationPacket] = []
for data in datas:
    verifs.append(SignedVerification(data.hash, 0))
    verifs[-1].sign(0, blsPrivKey)
    packets.append(VerificationPacket(data.hash, [0]))

#Create a MeritRemoval out of the conflicting Verifications.
mr: SignedMeritRemoval = SignedMeritRemoval(verifs[1], verifs[2])

#Generate a Block containing the MeritRemoval.
block = Block(
    BlockHeader(0, blockchain.last(),
                BlockHeader.createContents(packets, [mr]), 1, bytes(4),
                BlockHeader.createSketchCheck(bytes(4), packets), 0,
                blockchain.blocks[-1].header.time + 1200),
    BlockBody(
        packets, [mr],
        Signature.aggregate([
            verifs[0].signature, verifs[1].signature, verifs[2].signature,
            mr.signature
        ])))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Verify Competing Block " + str(len(blockchain.blocks)) + ".")
Esempio n. 21
0
#Add it.
blockchain.add(block)
print("Generated Hundred Twenty Block " + str(len(blockchain.blocks)) + ".")

#Create a DataDifficulty.
dataDiff: SignedDataDifficulty = SignedDataDifficulty(3, 0)
dataDiff.sign(0, blsPrivKey)

#Create a conflicting DataDifficulty with the same nonce.
dataDiffConflicting = SignedDataDifficulty(1, 0)
dataDiffConflicting.sign(0, blsPrivKey)

#Generate a Block containing the competing Data difficulty.
block = Block(
    BlockHeader(0, blockchain.last(),
                BlockHeader.createContents([], [dataDiffConflicting]), 1,
                bytes(4), bytes(32), 0,
                blockchain.blocks[-1].header.time + 1200),
    BlockBody([], [dataDiffConflicting], dataDiffConflicting.signature))
#Mine it.
block.mine(blsPrivKey, blockchain.difficulty())

#Add it.
blockchain.add(block)
print("Generated Hundred Twenty Block " + str(len(blockchain.blocks)) + ".")

result: Dict[str, Any] = {
    "blockchain": blockchain.toJSON(),
    "mempoolDataDiff": dataDiff.toSignedJSON(),
    "blockchainDataDiff": dataDiffConflicting.toJSON()
}
Esempio n. 22
0
#This will verify Meros properly handles out-of-order Elements included in a Block.
dataDiffs: List[SignedDataDifficulty] = [
    SignedDataDifficulty(1, 1),
    SignedDataDifficulty(2, 0)
]
for dataDiff in dataDiffs:
    dataDiff.sign(0, blsPrivKey)

for _ in range(2):
    block = Block(
        BlockHeader(
            0,
            blockchain.last(),
            #Used so the type checkers realize List[SignedDataDifficulty] is a viable List[Element].
            #pylint: disable=unnecessary-comprehension
            BlockHeader.createContents([], [e for e in dataDiffs]),
            0,
            bytes(4),
            bytes(32),
            0,
            blockchain.blocks[-1].header.time + 1200),
        #pylint: disable=unnecessary-comprehension
        BlockBody([], [e for e in dataDiffs],
                  Signature.aggregate([d.signature for d in dataDiffs])))
    block.mine(blsPrivKey, blockchain.difficulty())
    blockchain.add(block)

    #To verify the nonce isn't improperly set, add one more Data Difficulty with a nonce of 2.
    dataDiffs = [SignedDataDifficulty(4, 2)]
    dataDiffs[0].sign(0, blsPrivKey)
Esempio n. 23
0
secondVerif: SignedVerification = SignedVerification(second.hash)
secondVerif.sign(0, blsPrivKey)

packets: List[VerificationPacket] = [
  VerificationPacket(first.hash, [0]),
  VerificationPacket(second.hash, [0]),
]

#Generate another 6 Blocks.
#Next block should have the packets.
block: Block = Block(
  BlockHeader(
    0,
    merit.blockchain.last(),
    BlockHeader.createContents(packets),
    1,
    bytes(4),
    BlockHeader.createSketchCheck(bytes(4), packets),
    0,
    merit.blockchain.blocks[-1].header.time + 1200
  ),
  BlockBody(packets, [], Signature.aggregate([firstVerif.signature, secondVerif.signature]))
)
for _ in range(6):
  #Mine it.
  block.mine(blsPrivKey, merit.blockchain.difficulty())

  #Add it.
  merit.add(block)
  print("Generated Competing Finalized Block " + str(len(merit.blockchain.blocks) - 1) + ".")
Esempio n. 24
0
for data in datas:
    data.sign(edPrivKey)
    data.beat(spamFilter)

#Create Verifications for all 3.
verifs: List[SignedVerification] = []
for data in datas:
    verifs.append(SignedVerification(data.hash, 0))
    verifs[-1].sign(0, blsPrivKey)

#Create a MeritRemoval out of the conflicting Verifications.
mr: SignedMeritRemoval = SignedMeritRemoval(verifs[1], verifs[2])

#Generate a Block containing the MeritRemoval.
block = Block(
    BlockHeader(0, packetedChain.last(), BlockHeader.createContents([],
                                                                    [mr]), 1,
                bytes(4), bytes(32), 0,
                packetedChain.blocks[-1].header.time + 1200),
    BlockBody([], [mr], mr.signature))
#Mine it.
block.mine(blsPrivKey, packetedChain.difficulty())

#Add it.
packetedChain.add(block)
print("Generated Hundred Twenty Three Packet Block 1 " +
      str(len(packetedChain.blocks)) + ".")

#Create a MeritRemoval with random keys.
packeted: SignedMeritRemoval = SignedMeritRemoval(
    SignedMeritRemovalVerificationPacket(
        SignedVerificationPacket(verifs[1].hash), [