Esempio n. 1
0
        /// <summary>
        ///     Initial when user login + create token key to verify
        /// </summary>
        /// <param name="_key">Key generated and add to block</param>
        /// <param name="_username">User username</param>
        /// <returns>Redirect to Candidates view + token key</returns>
        public ActionResult create_BC(string _key, string _username)
        {
            var user  = db.Users.FirstOrDefault(x => x.Username.Equals(_username));
            var block = new BlockChainModel();

            if (user.Public_key == null)
            {
                block.initialBlock(_key, user);
            }


            //Generate a token
            Random rnd    = new Random();
            int    _num   = rnd.Next(0, 9);
            string _token = Membership.GeneratePassword(24, _num);

            //Encrypt token and send with random key to AR server
            string _keyToken = Guid.NewGuid().ToString("N");

            var _encryptToken = TokenModel.encryptToken(_token, _keyToken);
            var _encryptKey   = TokenModel.CreateKey(Encoding.Unicode.GetBytes(_keyToken)); // 64 bytes


            Session["UserSession"] = new UserSession {
                Username = _username
            };
            Session["TokenSession"] = new TokenSession {
                Token = _encryptToken, TokenKey = _encryptKey
            };
            Session["user_TokenSession"] = new UserSession {
                Token = _token
            };
            return(RedirectToAction("Index", "Candidates"));
        }
Esempio n. 2
0
    public async Task Set(DocumentId documentId, BlockChainModel blockChainModel, CancellationToken token = default)
    {
        HttpResponseMessage?response = await _httpClient.PostAsJsonAsync($"api/contract/set/{documentId.ToUrlEncoding()}", blockChainModel, token);

        response.VerifyNotNull("Null returned");
        response.EnsureSuccessStatusCode();
    }
    public async Task GivenNoContract_WhenCreated_ShouldVerify()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        var query = new QueryParameter()
        {
            Filter    = "test/unit-tests-smart",
            Recursive = false,
        };

        IReadOnlyList <string> search = (await client.Search(query).ReadNext()).Records;

        if (search.Any(x => x == (string)documentId))
        {
            await client.Delete(documentId);
        }

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        await client.Create(blkHeader);

        BlockChainModel model = await client.Get(documentId);

        model.Should().NotBeNull();
        model.Blocks.Should().NotBeNull();
        model.Blocks.Count.Should().Be(2);

        model.Blocks[0].Should().NotBeNull();
        model.Blocks[0].IsValid().Should().BeTrue();

        model.Blocks[1].Should().NotBeNull();
        model.Blocks[1].IsValid().Should().BeTrue();
        model.Blocks[1].DataBlock.Should().NotBeNull();
        model.Blocks[1].DataBlock.BlockType.Should().Be(typeof(BlkHeader).Name);

        bool isValid = await client.Validate(model);

        isValid.Should().BeTrue();


        BatchSet <string> searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        searchList.Records.Any(x => x.EndsWith(documentId.Path)).Should().BeTrue();

        (await client.Delete(documentId)).Should().BeTrue();

        searchList = await client.Search(query).ReadNext();

        searchList.Should().NotBeNull();
        searchList.Records.Any(x => x.EndsWith(documentId.Path)).Should().BeFalse();
    }
Esempio n. 4
0
        public async Task <IActionResult> Validate([FromBody] BlockChainModel blockChainModel, CancellationToken token)
        {
            blockChainModel.Verify();

            bool isValid = await _contractService.Validate(blockChainModel.ToBlockChain(), token);

            return(isValid ? Ok() : Conflict());
        }
Esempio n. 5
0
    public async Task Set(DocumentId documentId, BlockChainModel blockChain, CancellationToken token)
    {
        Document document = new DocumentBuilder()
                            .SetDocumentId(documentId.WithContainer(_container))
                            .SetData(blockChain)
                            .Build();

        await _artifactClient.Set(document, token);
    }
Esempio n. 6
0
        // GET: Block
        #region Index

        /// <summary>
        ///     Decrypt encrypted vote and passing data to blockchain
        /// </summary>
        /// <param name="_id">Block id</param>
        /// <param name="_dataBase64">Encrypted vote</param>
        /// <returns>Success vote</returns>
        public ActionResult Index(int _id, string _dataBase64)
        {
            var user = Session["UserSession"] as UserSession;

            if (user == null)
            {
                return(RedirectToAction("Index", "Vote"));
            }
            if (_dataBase64 == null)
            {
                return(RedirectToAction("SignIn", "Vote"));
            }
            else
            {
                var _data     = Convert.FromBase64String(_dataBase64);
                var _privKey  = Session["PrivateKeySession"] as PrivateKeySession;
                var _voteData = VoteModel.RSADecrypt(_data, _privKey.PrivateKey);

                var _temp  = Session["UserSession"] as UserSession;
                var _user  = db.Users.SingleOrDefault(x => x.Username.Equals(_temp.Username));
                var _block = db.Blocks.SingleOrDefault(x => x.Block_key.Equals(_user.Public_key));

                _block.Data            = _voteData;
                db.Entry(_block).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                var block = new BlockChainModel();
                block.isBlock(_user.Public_key, _block.Data, _block.Prev_ID, _block.Block_key);

                /////////////
                _user.Voted           = 1;
                db.Entry(_user).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                /////////////

                var candidate = db.Blocks.SingleOrDefault(x => x.Block_key == _voteData);
                if (candidate != null)
                {
                    if (candidate.Data == null)
                    {
                        candidate.Data            = "1";
                        db.Entry(candidate).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        candidate.Data            = (int.Parse(candidate.Data) + 1).ToString();
                        db.Entry(candidate).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                return(RedirectToAction("VoteSuccess", "Vote"));
            }
        }
Esempio n. 7
0
    // ////////////////////////////////////////////////////////////////////////////////////////////
    // CRUD methods

    public async Task <BlockChainModel?> Get(DocumentId documentId, CancellationToken token)
    {
        Document?document = await _artifactClient.Get(documentId.WithContainer(_container), token);

        if (document == null)
        {
            return(null);
        }

        BlockChainModel model = document.DeserializeData <BlockChainModel>();

        return(model);
    }
Esempio n. 8
0
        public ActionResult NewCandidate(AdminModel admin)
        {
            Block b = new Block()
            {
                Block_key = admin.Name,
                Network   = "2"
            };

            var block = new BlockChainModel();

            block.createBlock(b);


            return(View("Candidates"));
        }
Esempio n. 9
0
        public async Task <IActionResult> Set(string path, [FromBody] BlockChainModel blockChainModel, CancellationToken token)
        {
            blockChainModel.Verify();
            DocumentId documentId = DocumentIdTools.FromUrlEncoding(path);

            bool isValid = await _contractService.Validate(blockChainModel.ToBlockChain(), token);

            if (!isValid)
            {
                return(Conflict());
            }

            await _contractService.Set(documentId, blockChainModel, token);

            return(Ok());
        }
Esempio n. 10
0
        public async Task <IActionResult> Sign(string path, [FromBody] BlockChainModel blockChainModel, CancellationToken token)
        {
            blockChainModel.Verify();

            BlockChain blockChain = await _contractService.Sign(blockChainModel.ToBlockChain(), token);

            if (path == "model")
            {
                return(Ok(blockChain.ToBlockChainModel()));
            }

            DocumentId documentId = DocumentIdTools.FromUrlEncoding(path);
            await _contractService.Set(documentId, blockChain.ToBlockChainModel(), token);

            return(Ok());
        }
Esempio n. 11
0
    public async Task GivenBlockChain_WhenFile_WillRoundTrip()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        await Delete(documentId, false);

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        BlockChain blockChain = new BlockChainBuilder()
                                .SetPrincipleId(blkHeader.PrincipalId)
                                .Build()
                                .Add(blkHeader, blkHeader.PrincipalId);

        BlockChainModel signedBlockChainModel = await client.Sign(blockChain.ToBlockChainModel());

        signedBlockChainModel.Should().NotBeNull();

        await client.Set(documentId, signedBlockChainModel);

        BlockChainModel readBlockChainModel = await client.Get(documentId);

        readBlockChainModel.Should().NotBeNull();

        readBlockChainModel.Blocks.Count.Should().Be(signedBlockChainModel.Blocks.Count);
        readBlockChainModel.Blocks
        .Zip(signedBlockChainModel.Blocks)
        .All(x => x.First == x.Second)
        .Should().BeTrue();

        bool isValid = await client.Validate(documentId);

        isValid.Should().BeTrue();

        isValid = await client.Validate(readBlockChainModel);

        isValid.Should().BeTrue();

        await Delete(documentId, true);
    }
Esempio n. 12
0
        public ActionResult ReturnBlockChainCalculatedHashNonceAndPrev(BlockChainModel model)
        {
            int    nonce          = 0;
            string hash           = string.Empty;
            int    diffucultLevel = int.Parse(ConfigurationManager.AppSettings["DifficultyLevel"]);
            var    zeros          = GetHashRateZeros(diffucultLevel);

            while (true)
            {
                hash = Sha256.CreateSha256(model.Data + model.Prev + nonce);
                if (hash.Substring(0, diffucultLevel) == zeros)
                {
                    break;
                }
                nonce += 1;
            }
            model.Nonce = nonce;
            model.Hash  = hash;
            return(Json(model, JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
    public async Task GivenBlockChain_WhenSigned_FailedWithWrongSignature()
    {
        ContractClient client = TestApplication.GetContractClient();

        var documentId = new DocumentId("test/unit-tests-smart/contract1");

        var blkHeader = new BlkHeader
        {
            PrincipalId = "dev/user/[email protected]",
            DocumentId  = (string)documentId,
            Creator     = "test",
            Description = "test description",
        };

        BlockChain blockChain = new BlockChainBuilder()
                                .SetPrincipleId(blkHeader.PrincipalId)
                                .Build()
                                .Add(blkHeader, blkHeader.PrincipalId);

        BlockChainModel signedBlockChainModel = await client.Sign(blockChain.ToBlockChainModel());

        signedBlockChainModel.Should().NotBeNull();

        bool isValid = await client.Validate(signedBlockChainModel);


        // Modify signature
        signedBlockChainModel.Blocks[1] = signedBlockChainModel.Blocks[1] with {
            DataBlock = signedBlockChainModel.Blocks[1].DataBlock with {
                JwtSignature = "junk"
            }
        };

        isValid = await client.Validate(signedBlockChainModel);

        isValid.Should().BeFalse();
    }
Esempio n. 14
0
        public static BlockChain ToBlockChain(this BlockChainModel blockChainModel)
        {
            blockChainModel.VerifyNotNull(nameof(blockChainModel));

            return(new BlockChain(blockChainModel.Blocks));
        }
Esempio n. 15
0
 public static void Verify(this BlockChainModel blockChainModel)
 {
     blockChainModel.VerifyNotNull(nameof(blockChainModel));
     blockChainModel.Blocks.VerifyNotNull(nameof(blockChainModel.Blocks));
     blockChainModel.Blocks.ForEach(x => x.Verify());
 }