Esempio n. 1
0
        public ActivationStatusMutation()
        {
            Field <NonNullGraphType <BooleanGraphType> >("activateAccount",
                                                         arguments: new QueryArguments(
                                                             new QueryArgument <NonNullGraphType <StringGraphType> >
            {
                Name = "encodedActivationKey",
            }),
                                                         resolve: context =>
            {
                try
                {
                    string encodedActivationKey =
                        context.GetArgument <string>("encodedActivationKey");
                    NineChroniclesNodeService service = context.Source;
                    // FIXME: Private key may not exists at this moment.
                    PrivateKey privateKey       = service.PrivateKey;
                    ActivationKey activationKey = ActivationKey.Decode(encodedActivationKey);
                    BlockChain <NineChroniclesActionType> blockChain = service.Swarm.BlockChain;
                    IValue state = blockChain.GetState(activationKey.PendingAddress);

                    if (!(state is Bencodex.Types.Dictionary asDict))
                    {
                        context.Errors.Add(new ExecutionError("The given key was already expired."));
                        return(false);
                    }

                    var pendingActivationState = new PendingActivationState(asDict);
                    ActivateAccount action     = activationKey.CreateActivateAccount(
                        pendingActivationState.Nonce);

                    var actions = new NineChroniclesActionType[] { action };
                    blockChain.MakeTransaction(privateKey, actions);
                }
        public void CheckPermission()
        {
            var nonce  = new byte[] { 0x00, 0x01, 0x02, 0x03 };
            var pubKey = new PublicKey(
                ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1")
                );
            var pendingActivation = new PendingActivationState(nonce, pubKey);
            var action            = new CreatePendingActivation(pendingActivation);
            var adminAddress      = new Address("399bddF9F7B6d902ea27037B907B2486C9910730");
            var adminState        = new AdminState(adminAddress, 100);
            var state             = new State(ImmutableDictionary <Address, IValue> .Empty
                                              .Add(AdminState.Address, adminState.Serialize())
                                              );

            Assert.Throws <PolicyExpiredException>(
                () => action.Execute(new ActionContext()
            {
                BlockIndex     = 101,
                PreviousStates = state,
                Signer         = adminAddress,
            })
                );

            Assert.Throws <PermissionDeniedException>(
                () => action.Execute(new ActionContext()
            {
                BlockIndex     = 1,
                PreviousStates = state,
                Signer         = default,
        public void Execute()
        {
            var nonce  = new byte[] { 0x00, 0x01, 0x02, 0x03 };
            var pubKey = new PublicKey(
                ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1")
                );
            var pendingActivation = new PendingActivationState(nonce, pubKey);
            var action            = new CreatePendingActivation(pendingActivation);
            var adminAddress      = new Address("399bddF9F7B6d902ea27037B907B2486C9910730");
            var adminState        = new AdminState(adminAddress, 100);
            var state             = new State(ImmutableDictionary <Address, IValue> .Empty
                                              .Add(AdminState.Address, adminState.Serialize())
                                              );
            var actionContext = new ActionContext()
            {
                BlockIndex     = 1,
                PreviousStates = state,
                Signer         = adminAddress,
            };

            var nextState = action.Execute(actionContext);

            Assert.Equal(
                pendingActivation.Serialize(),
                nextState.GetState(pendingActivation.address)
                );
        }
 public InvalidSignatureException(
     SerializationInfo info, StreamingContext context
     ) : base(info, context)
 {
     byte[] rawPending = (byte[])info.GetValue(nameof(Pending), typeof(byte[]));
     Pending = new PendingActivationState(
         (Bencodex.Types.Dictionary) new Codec().Decode(rawPending)
         );
     Signature = (byte[])info.GetValue(nameof(Signature), typeof(byte[]));
 }
Esempio n. 5
0
        public void CreatePendingActivationsAfterRenewAdminState()
        {
            var random = new Random();
            var nonce  = new byte[40];

            random.NextBytes(nonce);
            var privateKey = new PrivateKey();

            var createPendingActivations = new CreatePendingActivations(new[]
            {
                new PendingActivationState(nonce, privateKey.PublicKey),
            });

            long blockIndex = _validUntil + 1;

            Assert.Throws <PolicyExpiredException>(() => createPendingActivations.Execute(new ActionContext
            {
                BlockIndex     = blockIndex,
                PreviousStates = _stateDelta,
                Signer         = _adminPrivateKey.ToAddress(),
            }));

            var newValidUntil = _validUntil + 1000;
            var action        = new RenewAdminState(newValidUntil);
            var stateDelta    = action.Execute(new ActionContext
            {
                BlockIndex     = blockIndex,
                PreviousStates = _stateDelta,
                Signer         = _adminPrivateKey.ToAddress(),
            });

            // After 100 blocks.
            blockIndex += 100;

            Assert.True(blockIndex < newValidUntil);
            stateDelta = createPendingActivations.Execute(new ActionContext
            {
                BlockIndex     = blockIndex,
                PreviousStates = stateDelta,
                Signer         = _adminPrivateKey.ToAddress(),
            });

            Address expectedPendingActivationStateAddress =
                PendingActivationState.DeriveAddress(nonce, privateKey.PublicKey);

            Assert.NotNull(stateDelta.GetState(expectedPendingActivationStateAddress));
        }
Esempio n. 6
0
        public void Serialize()
        {
            var nonce  = new byte[] { 0x00, 0x01, 0x02, 0x03 };
            var pubKey = new PublicKey(
                ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1")
                );
            var state = new PendingActivationState(nonce, pubKey);

            var serialized   = (Dictionary)state.Serialize();
            var deserialized = new PendingActivationState(serialized);

            Assert.Equal(
                new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"),
                deserialized.address
                );
            Assert.Equal(pubKey, deserialized.PublicKey);
            Assert.Equal(nonce, deserialized.Nonce);
        }
        public void PlainValue()
        {
            byte[]    nonce   = new byte[] { 0x00, 0x01, 0x02, 0x03 };
            PublicKey pubKey  = new PrivateKey().PublicKey;
            Address   address = PendingActivationState.DeriveAddress(nonce, pubKey);
            var       pv      = new List()
                                .Add(new List(address.Serialize(), (Binary)nonce, pubKey.Serialize()));

            var action = new CreatePendingActivations();

            action.LoadPlainValue(pv);

            var pvFromAction         = Assert.IsType <List>(action.PlainValue);
            var activationFromAction = Assert.IsType <List>(pvFromAction[0]);

            Assert.Equal(address, new Address((Binary)activationFromAction[0]));
            Assert.Equal(nonce, (Binary)activationFromAction[1]);
            Assert.Equal(pubKey, new PublicKey(((Binary)activationFromAction[2]).ByteArray));
        }
Esempio n. 8
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IAccountStateDelta state = context.PreviousStates;

            if (context.Rehearsal)
            {
                return(state
                       .SetState(ActivatedAccountsState.Address, MarkChanged)
                       .SetState(PendingAddress, MarkChanged));
            }

            CheckObsolete(BlockChain.Policy.BlockPolicySource.V100080ObsoleteIndex, context);

            if (!state.TryGetState(ActivatedAccountsState.Address, out Dictionary accountsAsDict))
            {
                throw new ActivatedAccountsDoesNotExistsException();
            }
            if (!state.TryGetState(PendingAddress, out Dictionary pendingAsDict))
            {
                throw new PendingActivationDoesNotExistsException(PendingAddress);
            }

            var accounts = new ActivatedAccountsState(accountsAsDict);
            var pending  = new PendingActivationState(pendingAsDict);

            if (pending.Verify(Signature))
            {
                // We left this log message to track activation history.
                // Please delete it if we have an API for evaluation results on the Libplanet side.
                Log.Information("{pendingAddress} is activated by {signer} now.", pending.address, context.Signer);
                return(state.SetState(
                           ActivatedAccountsState.Address,
                           accounts.AddAccount(context.Signer).Serialize()
                           ).SetState(
                           pending.address,
                           new Bencodex.Types.Null()
                           ));
            }
            else
            {
                throw new InvalidSignatureException(pending, Signature);
            }
        }
Esempio n. 9
0
        public static (ActivationKey, PendingActivationState) Create(
            PrivateKey privateKey,
            byte[] nonce
            )
        {
            if (privateKey is null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            if (nonce is null)
            {
                throw new ArgumentNullException(nameof(nonce));
            }

            var pendingActivation = new PendingActivationState(nonce, privateKey.PublicKey);
            var activationKey     = new ActivationKey(privateKey, pendingActivation.address);

            return(activationKey, pendingActivation);
        }
Esempio n. 10
0
        public ActivationStatusMutation(NineChroniclesNodeService service)
        {
            Field <NonNullGraphType <BooleanGraphType> >("activateAccount",
                                                         arguments: new QueryArguments(
                                                             new QueryArgument <NonNullGraphType <StringGraphType> >
            {
                Name = "encodedActivationKey",
            }),
                                                         resolve: context =>
            {
                try
                {
                    string encodedActivationKey =
                        context.GetArgument <string>("encodedActivationKey");
                    // FIXME: Private key may not exists at this moment.
                    if (!(service.MinerPrivateKey is { } privateKey))
                    {
                        throw new InvalidOperationException($"{nameof(privateKey)} is null.");
                    }

                    ActivationKey activationKey = ActivationKey.Decode(encodedActivationKey);
                    if (!(service.Swarm?.BlockChain is { } blockChain))
                    {
                        throw new InvalidOperationException($"{nameof(blockChain)} is null.");
                    }

                    IValue state = blockChain.GetState(activationKey.PendingAddress);

                    if (!(state is Bencodex.Types.Dictionary asDict))
                    {
                        context.Errors.Add(new ExecutionError("The given key was already expired."));
                        return(false);
                    }

                    var pendingActivationState = new PendingActivationState(asDict);
                    ActivateAccount action     = activationKey.CreateActivateAccount(
                        pendingActivationState.Nonce);

                    var actions = new NCAction[] { action };
                    blockChain.MakeTransaction(privateKey, actions);
                }
        public void Serialize()
        {
            var formatter = new BinaryFormatter();

            using var ms = new MemoryStream();
            var pending = new PendingActivationState(
                new byte[] { 0x00 },
                new PrivateKey().PublicKey
                );
            var exc = new InvalidSignatureException(
                pending,
                new byte[] { 0x01 }
                );

            formatter.Serialize(ms, exc);
            ms.Seek(0, SeekOrigin.Begin);
            var deserialized =
                (InvalidSignatureException)formatter.Deserialize(ms);

            Assert.Equal(exc.Pending.Serialize(), deserialized.Pending.Serialize());
            Assert.Equal(exc.Signature, deserialized.Signature);
        }
Esempio n. 12
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IAccountStateDelta state = context.PreviousStates;

            if (context.Rehearsal)
            {
                return(state
                       .SetState(ActivatedAccountsState.Address, MarkChanged)
                       .SetState(PendingAddress, MarkChanged));
            }

            if (!state.TryGetState(ActivatedAccountsState.Address, out Dictionary accountsAsDict))
            {
                throw new ActivatedAccountsDoesNotExistsException();
            }
            if (!state.TryGetState(PendingAddress, out Dictionary pendingAsDict))
            {
                throw new PendingActivationDoesNotExistsException(PendingAddress);
            }

            var accounts = new ActivatedAccountsState(accountsAsDict);
            var pending  = new PendingActivationState(pendingAsDict);

            if (pending.Verify(this))
            {
                return(state.SetState(
                           ActivatedAccountsState.Address,
                           accounts.AddAccount(context.Signer).Serialize()
                           ).SetState(
                           pending.address,
                           new Bencodex.Types.Null()
                           ));
            }
            else
            {
                throw new InvalidSignatureException(pending, Signature);
            }
        }
Esempio n. 13
0
        public void SerializeWithDotNetAPI()
        {
            var nonce  = new byte[] { 0x00, 0x01, 0x02, 0x03 };
            var pubKey = new PublicKey(
                ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1")
                );
            var state = new PendingActivationState(nonce, pubKey);

            var formatter = new BinaryFormatter();

            using var ms = new MemoryStream();
            formatter.Serialize(ms, state);
            ms.Seek(0, SeekOrigin.Begin);

            var deserialized = (PendingActivationState)formatter.Deserialize(ms);

            Assert.Equal(
                new Address("8d9f76aF8Dc5A812aCeA15d8bf56E2F790F47fd7"),
                deserialized.address
                );
            Assert.Equal(pubKey, deserialized.PublicKey);
            Assert.Equal(nonce, deserialized.Nonce);
        }
Esempio n. 14
0
        public override IAccountStateDelta Execute(IActionContext context)
        {
            IAccountStateDelta state            = context.PreviousStates;
            Address            activatedAddress = context.Signer.Derive(ActivationKey.DeriveKey);

            if (context.Rehearsal)
            {
                return(state
                       .SetState(activatedAddress, MarkChanged)
                       .SetState(PendingAddress, MarkChanged));
            }

            if (!(state.GetState(activatedAddress) is null))
            {
                throw new AlreadyActivatedException($"{context.Signer} already activated.");
            }
            if (!state.TryGetState(PendingAddress, out Dictionary pendingAsDict))
            {
                throw new PendingActivationDoesNotExistsException(PendingAddress);
            }

            var pending = new PendingActivationState(pendingAsDict);

            if (pending.Verify(this))
            {
                // We left this log message to track activation history.
                // Please delete it if we have an API for evaluation results on the Libplanet side.
                Log.Information("{pendingAddress} is activated by {signer} now.", pending.address, context.Signer);
                return(state
                       .SetState(activatedAddress, true.Serialize())
                       .SetState(pending.address, new Bencodex.Types.Null()));
            }
            else
            {
                throw new InvalidSignatureException(pending, Signature);
            }
        }
Esempio n. 15
0
 public InvalidSignatureException(PendingActivationState pending, byte[] signature)
 {
     Pending   = pending;
     Signature = signature;
 }
Esempio n. 16
0
 public CreatePendingActivation(PendingActivationState activationKey)
 {
     PendingActivation = activationKey;
 }
Esempio n. 17
0
        public override void LoadPlainValue(IValue plainValue)
        {
            var asDict = ((Bencodex.Types.Dictionary)plainValue);

            PendingActivation = new PendingActivationState((Dictionary)asDict["pending_activation"]);
        }