/// <summary>
        /// Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
        /// </summary>
        public bool IsSlashableAttestationData(AttestationData data1, AttestationData data2)
        {
            bool isDoubleVote   = data1.Target.Epoch == data2.Target.Epoch && !data1.Equals(data2);
            bool isSurroundVote = data1.Source.Epoch < data2.Source.Epoch && data2.Target.Epoch < data1.Target.Epoch;
            bool isSlashable    = isDoubleVote || isSurroundVote;

            return(isSlashable);
        }
Exemple #2
0
        /// <summary>
        /// Return the set of attesting indices corresponding to ``data`` and ``bits``.
        /// </summary>
        public IReadOnlyList <ValidatorIndex> GetAttestingIndices(BeaconState state, AttestationData data, BitArray bits)
        {
            IReadOnlyList <ValidatorIndex> committee = GetBeaconCommittee(state, data.Slot, data.Index);

            return(committee
                   .Where((x, index) => bits[index])
                   .ToList()
                   .AsReadOnly());
        }
Exemple #3
0
        /// <summary>
        /// Check if ``data_1`` and ``data_2`` are slashable according to Casper FFG rules.
        /// </summary>
        public bool IsSlashableAttestationData(AttestationData data1, AttestationData data2)
        {
            bool isSlashable =
                // Double vote
                (data1.Target.Epoch == data2.Target.Epoch && !data1.Equals(data2))
                // Surround vote
                || (data1.Source.Epoch < data2.Source.Epoch && data2.Target.Epoch < data1.Target.Epoch);

            return(isSlashable);
        }
        private static AttestationData DecodeAttestationData(Span <byte> span, ref int offset)
        {
            AttestationData container = new AttestationData();

            container.Slot            = DecodeSlot(span, ref offset);
            container.CommitteeIndex  = DecodeCommitteeIndex(span, ref offset);
            container.BeaconBlockRoot = DecodeSha256(span, ref offset);
            container.Source          = DecodeCheckpoint(span, ref offset);
            container.Target          = DecodeCheckpoint(span, ref offset);
            return(container);
        }
Exemple #5
0
        private static void TestAttestationDataSsz(byte[] serialized, UInt256 expectedMerkleRoot, string testCaseDir)
        {
            AttestationData container = Nethermind.Ssz.Ssz.DecodeAttestationData(serialized);

            byte[] again = new byte[serialized.Length];
            Nethermind.Ssz.Ssz.Encode(again, container);
            Assert.AreEqual(serialized.ToHexString(), again.ToHexString(), testCaseDir);

            Merkle.Ize(out UInt256 root, container);
            Assert.AreEqual(expectedMerkleRoot, root);
        }
        private static AttestationData DecodeAttestationData(ReadOnlySpan <byte> span, ref int offset)
        {
            Slot            slot            = DecodeSlot(span, ref offset);
            CommitteeIndex  index           = DecodeCommitteeIndex(span, ref offset);
            Root            beaconBlockRoot = DecodeRoot(span, ref offset);
            Checkpoint      source          = DecodeCheckpoint(span, ref offset);
            Checkpoint      target          = DecodeCheckpoint(span, ref offset);
            AttestationData container       = new AttestationData(slot, index, beaconBlockRoot, source, target);

            return(container);
        }
Exemple #7
0
        public static void Ize(out UInt256 root, AttestationData container)
        {
            Merkleizer merkleizer = new Merkleizer(3);

            merkleizer.Feed(container.Slot);
            merkleizer.Feed(container.CommitteeIndex);
            merkleizer.Feed(container.BeaconBlockRoot);
            merkleizer.Feed(container.Source);
            merkleizer.Feed(container.Target);
            merkleizer.CalculateRoot(out root);
        }
Exemple #8
0
        public static IndexedAttestation DecodeIndexedAttestation(ReadOnlySpan <byte> span)
        {
            int offset = 0;

            DecodeDynamicOffset(span, ref offset, out int dynamicOffset1);
            ValidatorIndex[]   attestingIndices = DecodeValidatorIndexes(span.Slice(dynamicOffset1));
            AttestationData    data             = DecodeAttestationData(span, ref offset);
            BlsSignature       signature        = DecodeBlsSignature(span, ref offset);
            IndexedAttestation container        = new IndexedAttestation(attestingIndices, data, signature);

            return(container);
        }
Exemple #9
0
        public static PendingAttestation DecodePendingAttestation(Span <byte> span)
        {
            int offset = 0;

            DecodeDynamicOffset(span, ref offset, out int dynamicOffset);
            BitArray           aggregationBits    = DecodeBitlist(span.Slice(dynamicOffset, span.Length - dynamicOffset));
            AttestationData    data               = DecodeAttestationData(span, ref offset);
            Slot               inclusionDelay     = DecodeSlot(span, ref offset);
            ValidatorIndex     proposerIndex      = DecodeValidatorIndex(span, ref offset);
            PendingAttestation pendingAttestation = new PendingAttestation(aggregationBits, data, inclusionDelay, proposerIndex);

            return(pendingAttestation);
        }
        private static IEnumerable <SszElement> GetValues(AttestationData item)
        {
            yield return(item.Slot.ToSszBasicElement());

            yield return(item.Index.ToSszBasicElement());

            // LMD GHOST vote
            yield return(item.BeaconBlockRoot.ToSszBasicVector());

            // FFG vote
            yield return(item.Source.ToSszContainer());

            yield return(item.Target.ToSszContainer());
        }
Exemple #11
0
        public void Can_merkleize_attestion_data()
        {
            // arrange
            AttestationData attestationData = new AttestationData(
                Slot.One,
                new CommitteeIndex(2),
                new Root(Enumerable.Repeat((byte)0x12, 32).ToArray()),
                new Checkpoint(
                    new Epoch(3),
                    new Root(Enumerable.Repeat((byte)0x34, 32).ToArray())
                    ),
                new Checkpoint(
                    new Epoch(4),
                    new Root(Enumerable.Repeat((byte)0x56, 32).ToArray())
                    )
                );

            // act
            Merkleizer merklezier = new Merkleizer(0);

            merklezier.Feed(attestationData);
            UInt256     root  = merklezier.CalculateRoot();
            Span <byte> bytes = MemoryMarshal.Cast <UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1));

            // assert
            byte[] expected = HashUtility.Hash(
                HashUtility.Hash(
                    HashUtility.Hash(
                        HashUtility.Chunk(new byte[] { 0x01 }), // slot
                        HashUtility.Chunk(new byte[] { 0x02 })  // committee
                        ),
                    HashUtility.Hash(
                        Enumerable.Repeat((byte)0x12, 32).ToArray(), // beacon block root
                        HashUtility.Hash(                            // source
                            HashUtility.Chunk(new byte[] { 0x03 }),
                            Enumerable.Repeat((byte)0x34, 32).ToArray()
                            )
                        )
                    ),
                HashUtility.Merge(
                    HashUtility.Hash( // target
                        HashUtility.Chunk(new byte[] { 0x04 }),
                        Enumerable.Repeat((byte)0x56, 32).ToArray()
                        ),
                    HashUtility.ZeroHashes(0, 2)
                    )
                ).ToArray();
            bytes.ToArray().ShouldBe(expected);
        }
        public static void Encode(Span <byte> span, AttestationData container)
        {
            if (span.Length != Ssz.AttestationDataLength)
            {
                ThrowTargetLength <AttestationData>(span.Length, Ssz.AttestationDataLength);
            }

            int offset = 0;

            Encode(span, container.Slot, ref offset);
            Encode(span, container.Index, ref offset);
            Encode(span, container.BeaconBlockRoot, ref offset);
            Encode(span, container.Source, ref offset);
            Encode(span, container.Target, ref offset);
        }
        public static Attestation DecodeAttestation(ReadOnlySpan <byte> span)
        {
            int offset = 0;

            // static part
            DecodeDynamicOffset(span, ref offset, out int dynamicOffset1);
            AttestationData data      = DecodeAttestationData(span, ref offset);
            BlsSignature    signature = DecodeBlsSignature(span, ref offset);

            // var part
            BitArray aggregationBits = DecodeBitlist(span.Slice(dynamicOffset1, span.Length - dynamicOffset1));

            Attestation container = new Attestation(aggregationBits, data, signature);

            return(container);
        }
        public static AttestationData DecodeAttestationData(Span <byte> span)
        {
            if (span.Length != AttestationData.SszLength)
            {
                ThrowSourceLength <AttestationData>(span.Length, AttestationData.SszLength);
            }

            int             offset    = 0;
            AttestationData container = new AttestationData();

            container.Slot            = DecodeSlot(span, ref offset);
            container.CommitteeIndex  = DecodeCommitteeIndex(span, ref offset);
            container.BeaconBlockRoot = DecodeSha256(span, ref offset);
            container.Source          = DecodeCheckpoint(span, ref offset);
            container.Target          = DecodeCheckpoint(span, ref offset);
            return(container);
        }
        public static AttestationData DecodeAttestationData(Span <byte> span)
        {
            if (span.Length != Ssz.AttestationDataLength)
            {
                ThrowSourceLength <AttestationData>(span.Length, Ssz.AttestationDataLength);
            }

            int             offset    = 0;
            AttestationData container = new AttestationData(
                DecodeSlot(span, ref offset),
                DecodeCommitteeIndex(span, ref offset),
                DecodeRoot(span, ref offset),
                DecodeCheckpoint(span, ref offset),
                DecodeCheckpoint(span, ref offset));

            return(container);
        }
Exemple #16
0
        public void Attestation_data_there_and_back()
        {
            AttestationData container = new AttestationData(
                new Slot(1),
                new CommitteeIndex(2),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(1), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString));

            Span <byte> encoded = new byte[Ssz.AttestationDataLength];

            Ssz.Encode(encoded, container);
            AttestationData decoded = Ssz.DecodeAttestationData(encoded);

            Assert.AreEqual(container, decoded);

            Span <byte> encodedAgain = new byte[Ssz.AttestationDataLength];

            Ssz.Encode(encodedAgain, decoded);
            Assert.True(Bytes.AreEqual(encodedAgain, encoded));

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #17
0
        public void Indexed_attestation_there_and_back()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(2),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(1), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString));

            IndexedAttestation container = new IndexedAttestation(
                new ValidatorIndex[3],
                data,
                TestSig1);

            Span <byte> encoded = new byte[Ssz.IndexedAttestationLength(container)];

            Ssz.Encode(encoded, container);
            IndexedAttestation decoded = Ssz.DecodeIndexedAttestation(encoded);

            decoded.ShouldBe(container);

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #18
0
        public void Attestation_there_and_back()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(2),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(1), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString));

            Attestation container = new Attestation(
                new BitArray(new byte[] { 1, 2, 3 }),
                data,
                TestSig1);

            Span <byte> encoded = new byte[Ssz.AttestationLength(container)];

            Ssz.Encode(encoded, container);
            Attestation decoded = Ssz.DecodeAttestation(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #19
0
        // def get_valid_attestation(spec, state, slot=None, index=None, signed=False):
        public static Attestation GetValidAttestation(IServiceProvider testServiceProvider, BeaconState state, Slot?optionalSlot, CommitteeIndex?optionalIndex, bool signed)
        {
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            Slot           slot  = optionalSlot ?? state.Slot;
            CommitteeIndex index = optionalIndex ?? CommitteeIndex.Zero;

            AttestationData attestationData = BuildAttestationData(testServiceProvider, state, slot, index);

            IReadOnlyList <ValidatorIndex> beaconCommittee = beaconStateAccessor.GetBeaconCommittee(state, attestationData.Slot, attestationData.Index);

            int         committeeSize   = beaconCommittee.Count;
            BitArray    aggregationBits = new BitArray(committeeSize);
            Attestation attestation     = new Attestation(aggregationBits, attestationData, BlsSignature.Zero);

            FillAggregateAttestation(state, attestation, beaconStateAccessor);

            if (signed)
            {
                SignAttestation(testServiceProvider, state, attestation);
            }

            return(attestation);
        }
Exemple #20
0
        public void Pending_attestation_there_and_back()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(2),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(1), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString));

            PendingAttestation container = new PendingAttestation(
                new BitArray(new byte[3]),
                data,
                new Slot(7),
                new ValidatorIndex(13));

            Span <byte> encoded = new byte[Ssz.PendingAttestationLength(container)];

            Ssz.Encode(encoded, container);
            PendingAttestation?decoded = Ssz.DecodePendingAttestation(encoded);

            decoded.ShouldBe(container);

            Merkle.Ize(out UInt256 root, container);
        }
        public void Attester_slashing_there_and_back()
        {
            AttestationData data = new AttestationData();

            data.Slot            = new Slot(1);
            data.CommitteeIndex  = new CommitteeIndex(2);
            data.BeaconBlockRoot = Sha256.OfAnEmptyString;
            data.Source          = new Checkpoint(new Epoch(1), Sha256.OfAnEmptyString);
            data.Target          = new Checkpoint(new Epoch(2), Sha256.OfAnEmptyString);

            IndexedAttestation indexedAttestation1 = new IndexedAttestation();

            indexedAttestation1.AttestingIndices = new ValidatorIndex[3];
            indexedAttestation1.Data             = data;
            indexedAttestation1.Signature        = BlsSignature.TestSig1;

            IndexedAttestation indexedAttestation2 = new IndexedAttestation();

            indexedAttestation2.AttestingIndices = new ValidatorIndex[5];
            indexedAttestation2.Data             = data;
            indexedAttestation2.Signature        = BlsSignature.TestSig1;

            AttesterSlashing container = new AttesterSlashing();

            container.Attestation1 = indexedAttestation1;
            container.Attestation2 = indexedAttestation2;

            Span <byte> encoded = new byte[AttesterSlashing.SszLength(container)];

            Ssz.Encode(encoded, container);
            AttesterSlashing?decoded = Ssz.DecodeAttesterSlashing(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
        public void Attestation_data_there_and_back()
        {
            AttestationData container = new AttestationData();

            container.Slot            = new Slot(1);
            container.CommitteeIndex  = new CommitteeIndex(2);
            container.BeaconBlockRoot = Sha256.OfAnEmptyString;
            container.Source          = new Checkpoint(new Epoch(1), Sha256.OfAnEmptyString);
            container.Target          = new Checkpoint(new Epoch(2), Sha256.OfAnEmptyString);

            Span <byte> encoded = new byte[AttestationData.SszLength];

            Ssz.Encode(encoded, container);
            AttestationData decoded = Ssz.DecodeAttestationData(encoded);

            Assert.AreEqual(container, decoded);

            Span <byte> encodedAgain = new byte[AttestationData.SszLength];

            Ssz.Encode(encodedAgain, decoded);
            Assert.True(Bytes.AreEqual(encodedAgain, encoded));

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #23
0
        public SszBeaconBlockBodyBenchmark()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(4),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(3), Sha256.RootOfAnEmptyString));

            Attestation attestation = new Attestation(
                new BitArray(new byte[5]),
                data,
                TestSig1
                );

            DepositData depositData = new DepositData(
                TestKey1,
                Sha256.Bytes32OfAnEmptyString,
                new Gwei(7),
                TestSig1);

            Deposit deposit = new Deposit(
                new Bytes32[Ssz.DepositContractTreeDepth + 1],
                depositData);

            IndexedAttestation indexedAttestation1 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            IndexedAttestation indexedAttestation2 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            AttesterSlashing slashing = new AttesterSlashing(indexedAttestation1, indexedAttestation2);

            Eth1Data eth1Data = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                9,
                Sha256.Bytes32OfAnEmptyString);

            Attestation[] attestations = new Attestation[3];
            attestations[1] = attestation;

            Deposit[] deposits = new Deposit[3];
            deposits[2] = deposit;

            Bytes32 graffiti = new Bytes32(new byte[32]);

            AttesterSlashing[] attesterSlashings = new AttesterSlashing[3];
            attesterSlashings[0] = slashing;

            ProposerSlashing[] proposerSlashings = new ProposerSlashing[10];

            BlsSignature randaoReveal = TestSig1;

            SignedVoluntaryExit[] signedVoluntaryExits = new SignedVoluntaryExit[11];

            _body = new BeaconBlockBody(randaoReveal,
                                        eth1Data,
                                        graffiti,
                                        proposerSlashings,
                                        attesterSlashings,
                                        attestations,
                                        deposits,
                                        signedVoluntaryExits);

            _encoded = new byte[Ssz.BeaconBlockBodyLength(_body)];
        }
 public Root HashTreeRoot(AttestationData attestationData)
 {
     throw new NotImplementedException();
 }
 public static SszContainer ToSszContainer(this AttestationData item)
 {
     return(new SszContainer(GetValues(item)));
 }
        public static Hash32 HashTreeRoot(this AttestationData item)
        {
            var tree = new SszTree(item.ToSszContainer());

            return(new Hash32(tree.HashTreeRoot()));
        }
Exemple #27
0
        public static BlsSignature SignAggregateAttestation(IServiceProvider testServiceProvider, BeaconState state, AttestationData attestationData, IEnumerable <ValidatorIndex> participants)
        {
            var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            var privateKeys = TestKeys.PrivateKeys(timeParameters).ToList();
            var signatures  = new List <BlsSignature>();

            foreach (var validatorIndex in participants)
            {
                var privateKey = privateKeys[(int)(ulong)validatorIndex];
                var signature  = GetAttestationSignature(testServiceProvider, state, attestationData, privateKey, custodyBit: false);
                signatures.Add(signature);
            }

            return(TestSecurity.BlsAggregateSignatures(signatures));
        }
Exemple #28
0
        public static BlsSignature GetAttestationSignature(IServiceProvider testServiceProvider, BeaconState state, AttestationData attestationData, byte[] privateKey, bool custodyBit)
        {
            var signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            var message     = new AttestationDataAndCustodyBit(attestationData, custodyBit);
            var messageHash = message.HashTreeRoot();
            var domain      = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconAttester, attestationData.Target.Epoch);
            var signature   = TestSecurity.BlsSign(messageHash, privateKey, domain);

            return(signature);
        }
Exemple #29
0
        private static AttestationData BuildAttestationData(IServiceProvider testServiceProvider, BeaconState state, Slot slot, CommitteeIndex index)
        {
            var beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            if (state.Slot > slot)
            {
                throw new ArgumentOutOfRangeException(nameof(slot), slot, $"Slot cannot be greater than state slot {state.Slot}.");
            }

            Hash32 blockRoot;

            if (slot == state.Slot)
            {
                var nextBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, false);
                blockRoot = nextBlock.ParentRoot;
            }
            else
            {
                blockRoot = beaconStateAccessor.GetBlockRootAtSlot(state, slot);
            }

            Hash32 epochBoundaryRoot;
            var    currentEpoch          = beaconStateAccessor.GetCurrentEpoch(state);
            var    currentEpochStartSlot = beaconChainUtility.ComputeStartSlotOfEpoch(currentEpoch);

            if (slot < currentEpochStartSlot)
            {
                var previousEpoch = beaconStateAccessor.GetPreviousEpoch(state);
                epochBoundaryRoot = beaconStateAccessor.GetBlockRoot(state, previousEpoch);
            }
            else if (slot == currentEpochStartSlot)
            {
                epochBoundaryRoot = blockRoot;
            }
            else
            {
                epochBoundaryRoot = beaconStateAccessor.GetBlockRoot(state, currentEpoch);
            }

            Epoch  sourceEpoch;
            Hash32 sourceRoot;

            if (slot < currentEpochStartSlot)
            {
                sourceEpoch = state.PreviousJustifiedCheckpoint.Epoch;
                sourceRoot  = state.PreviousJustifiedCheckpoint.Root;
            }
            else
            {
                sourceEpoch = state.CurrentJustifiedCheckpoint.Epoch;
                sourceRoot  = state.CurrentJustifiedCheckpoint.Root;
            }

            //Crosslink parentCrosslink;
            //if (epochOfSlot == currentEpoch)
            //{
            //    parentCrosslink = state.CurrentCrosslinks[(int)(ulong)shard];
            //}
            //else
            //{
            //    throw new NotImplementedException();
            //}

            var slotEpoch       = beaconChainUtility.ComputeEpochAtSlot(slot);
            var attestationData = new AttestationData(
                slot,
                index,
                blockRoot,
                new Checkpoint(sourceEpoch, sourceRoot),
                new Checkpoint(slotEpoch, epochBoundaryRoot));

            return(attestationData);
        }
 public Hash32 HashTreeRoot(AttestationData attestationData)
 {
     Merkle.Ize(out UInt256 root, attestationData);
     Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1));
     return new Hash32(bytes);
 }