Ejemplo n.º 1
0
        private void InitKeys()
        {
            var key = SiaSkynetClient.GenerateKeys(seedPhrase);

            privateKey = key.privateKey;
            publicKey  = key.publicKey;
        }
Ejemplo n.º 2
0
        public async Task <MetaMaskLogin?> GetStoredhash(string address)
        {
            string encryptedStoredLogin = await GetEncryptedMetamaskHash();

            if (!string.IsNullOrEmpty(encryptedStoredLogin))
            {
                try
                {
                    var key = SiaSkynetClient.GenerateKeys(address);

                    var cipherData = Utils.HexStringToByteArray(encryptedStoredLogin);
                    var decrypt    = Utils.Decrypt(cipherData, key.privateKey);
                    var dString    = System.Text.Encoding.UTF8.GetString(decrypt);

                    MetaMaskLogin?storedLogin = JsonSerializer.Deserialize <MetaMaskLogin>(dString);

                    if (storedLogin?.address != address)
                    {
                        return(null);
                    }

                    return(storedLogin);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            return(null);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Invalid args - should only be the datakey and the file containing the data you want to put");
                return;
            }

            SiaSkynet.SiaSkynetClient c = new SiaSkynetClient();
            bool   seedFileExists       = File.Exists(@".\seed.txt");
            string seed = "";

            if (seedFileExists)
            {
                Console.WriteLine("seed.txt found, generating keys off it");
                seed = System.IO.File.ReadAllText(@".\seed.txt");
            }
            else
            {
                string generatedSeed = GetUniqueString(64);
                System.IO.File.WriteAllText(@".\seed.txt", generatedSeed);
                seed = generatedSeed;
                Console.WriteLine("seed.txt not found, generating a seed randomly and writing it to seed.txt");
            }
            var keys = SiaSkynetClient.GenerateKeys(seed).Result;

            Console.WriteLine("Updating registry at " + args[0] + " with content in " + args[1]);
            string content = System.IO.File.ReadAllText(args[1]);
            bool   r       = c.SkyDbSet(keys.privateKey, keys.publicKey, args[0], content).Result;

            Console.WriteLine("Registry now contains:");
            string actualContent = c.SkyDbGetAsString(keys.publicKey, args[0]).Result;

            Console.WriteLine(actualContent);
        }
Ejemplo n.º 4
0
        public void TestKeys()
        {
            var key  = SiaSkynetClient.GenerateKeys(_testSeed);
            var key2 = SiaSkynetClient.GenerateKeys(_testSeed);

            Assert.IsNotNull(key.publicKey);
        }
Ejemplo n.º 5
0
        public SkyDocsService(DfinityService dfinityService, IHttpClientFactory httpClientFactory)
        {
            this.dfinityService    = dfinityService;
            this.httpClientFactory = httpClientFactory;

            var httpClient = httpClientFactory.CreateClient("API");

            client = new SiaSkynetClient(httpClient);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get document from SkyDB based on ID as key
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task <Document?> GetDocument(DocumentSummary sum)
        {
            try
            {
                Error = null;
                Console.WriteLine("Loading document");
                if (IsDfinityNetwork || sum.StorageSource == StorageSource.Dfinity)
                {
                    string?json = await dfinityService.GetValue(sum.Id.ToString());

                    if (string.IsNullOrEmpty(json))
                    {
                        return(new Document());
                    }

                    var document = JsonSerializer.Deserialize <Document>(json) ?? new Document();
                    sum.Title        = document.Title;
                    sum.PreviewImage = document.PreviewImage;
                    sum.CreatedDate  = document.CreatedDate;
                    sum.ModifiedDate = document.ModifiedDate;

                    return(document);
                }
                else
                {
                    var encryptedData = await client.SkyDbGet(sum.PublicKey, new RegistryKey(sum.Id.ToString()), TimeSpan.FromSeconds(10));

                    if (!encryptedData.HasValue)
                    {
                        return(new Document());
                    }
                    else
                    {
                        //Decrypt data
                        var key       = SiaSkynetClient.GenerateKeys(sum.ContentSeed);
                        var jsonBytes = Utils.Decrypt(encryptedData.Value.file, key.privateKey);
                        var json      = Encoding.UTF8.GetString(jsonBytes);

                        var document = JsonSerializer.Deserialize <Document>(json) ?? new Document();
                        sum.Title        = document.Title;
                        sum.PreviewImage = document.PreviewImage;
                        sum.CreatedDate  = document.CreatedDate;
                        sum.ModifiedDate = document.ModifiedDate;

                        document.Revision = encryptedData.Value.registryEntry?.Revision ?? 0;

                        return(document);
                    }
                }
            }
            catch
            {
                Error = $"Unable to load document from {CurrentNetwork}. Please try again.";
            }

            return(null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Login with username/password
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void Login(string username, string password)
        {
            string seedPhrase = $"{username}-{password}-{salt}";
            var    key        = SiaSkynetClient.GenerateKeys(seedPhrase);

            privateKey = key.privateKey;
            publicKey  = key.publicKey;

            IsLoggedIn = true;
        }
Ejemplo n.º 8
0
 public CmsFileStorageService(IOptions <SkynetConfig> skynetConfig)
 {
     if (!string.IsNullOrEmpty(skynetConfig.Value.BaseUrl))
     {
         _client = new SiaSkynetClient(skynetConfig.Value.BaseUrl);
     }
     else
     {
         _client = new SiaSkynetClient();
     }
 }
Ejemplo n.º 9
0
        public async Task TestGetRegistry()
        {
            var key = SiaSkynetClient.GenerateKeys(_testSeed);

            RegistryKey dataKey = new RegistryKey("t3");

            var result = await _client.GetRegistry(key.publicKey, dataKey);

            Assert.IsNotNull(result);
            Assert.AreEqual("IADUs8d9CQjUO34LmdaaNPK_STuZo24rpKVfYW3wPPM2uQ", result.GetDataAsString());
        }
Ejemplo n.º 10
0
        public async Task TestSkyDbUpdateSimple()
        {
            string      newData = Guid.NewGuid().ToString();
            var         key     = SiaSkynetClient.GenerateKeys("my private key seed");
            RegistryKey dataKey = new RegistryKey("datakey");


            var success = await _client.SkyDbSetAsString(key.privateKey, key.publicKey, dataKey, newData);

            string result = await _client.SkyDbGetAsString(key.publicKey, dataKey);

            Assert.IsTrue(success);
            Assert.AreEqual(newData, result);
        }
Ejemplo n.º 11
0
        public void SetPortalDomain(string scheme, string domain)
        {
            string[] urlParts = domain.Split('.');

            //Only take last two parts
            var lastParts = urlParts.Skip(urlParts.Count() - 2).Take(2);

            if (lastParts.Count() == 2)
            {
                var url = $"{scheme}://{string.Join('.', lastParts)}";
                Console.WriteLine($"Using API domain: {url}");
                client = new SiaSkynetClient(url);
            }
        }
Ejemplo n.º 12
0
        public async Task TestSetRegistry()
        {
            string dataKey  = Guid.NewGuid().ToString();
            int    revision = 0;
            string data     = "IADUs8d9CQjUO34LmdaaNPK_STuZo24rpKVfYW3wPPM2uQ"; //Sia logo

            var key = SiaSkynetClient.GenerateKeys(_testSeed);

            RegistryEntry reg = new RegistryEntry(new RegistryKey(dataKey));

            reg.SetData(data);
            reg.Revision = revision;

            var success = await _client.SetRegistry(key.privateKey, key.publicKey, reg);

            Assert.IsTrue(success);
        }
Ejemplo n.º 13
0
        public async Task SaveStoredHash(MetaMaskLogin storedLogin)
        {
            try
            {
                var key = SiaSkynetClient.GenerateKeys(storedLogin.address);

                string jsonString = JsonSerializer.Serialize(storedLogin);
                var    encrypted  = Utils.Encrypt(System.Text.Encoding.UTF8.GetBytes(jsonString), key.privateKey);
                var    hexString  = BitConverter.ToString(encrypted).Replace("-", "");

                await localStorageService.SetItemAsStringAsync(MetaMaskLocalStorageKey, hexString);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 14
0
        public void BasicEncryptionTest()
        {
            var key  = SiaSkynetClient.GenerateKeys("test");
            var key2 = SiaSkynetClient.GenerateKeys("bar");

            var testValue = "this is not encrypted";

            var encrypted = Utils.Encrypt(System.Text.Encoding.UTF8.GetBytes(testValue), key.privateKey);
            var eString   = System.Text.Encoding.UTF8.GetString(encrypted);

            Assert.AreNotEqual(testValue, eString);


            var decrypt = Utils.Decrypt(encrypted, key.privateKey);
            var dString = System.Text.Encoding.UTF8.GetString(decrypt);

            Assert.AreEqual(testValue, dString);
        }
Ejemplo n.º 15
0
        public async Task <string> StoreMessage([FromBody] AddMessageRequest req)
        {
            string address = req.Address.ToLowerInvariant();

            string seed = $"{secretConfig.SkynetSeed}-{address}";
            var    key  = SiaSkynetClient.GenerateKeys(seed);

            var encrypted = Utils.Encrypt(System.Text.Encoding.UTF8.GetBytes(req.Message), key.privateKey);

            using (Stream stream = new MemoryStream(encrypted))
            {
                //Save data to Skynet file
                var response = await client.UploadFileAsync("secret.dat", stream);

                var link = response.Skylink;

                return(link);
            }
        }
Ejemplo n.º 16
0
        public async Task TestForcedRevision()
        {
            string      data     = Guid.NewGuid().ToString();
            var         key      = SiaSkynetClient.GenerateKeys("my private key seed");
            RegistryKey dataKey  = new RegistryKey("datakey" + Guid.NewGuid());
            int         revision = 5;

            var success = await _client.SkyDbSet(key.privateKey, key.publicKey, dataKey, Encoding.UTF8.GetBytes(data), revision);

            var result = await _client.SkyDbGet(key.publicKey, dataKey);

            Assert.IsTrue(success);
            Assert.AreEqual(revision, result.Value.registryEntry.Revision);


            var stringResult = Encoding.UTF8.GetString(result.Value.file);

            Assert.AreEqual(data, stringResult);
        }
Ejemplo n.º 17
0
        public async Task TestRegistryUpdate()
        {
            RegistryKey dataKey = new RegistryKey("regtest");
            var         key     = SiaSkynetClient.GenerateKeys(_testSeed);

            var success = await _client.UpdateRegistry(key.privateKey, key.publicKey, dataKey, "update1");

            await Task.Delay(TimeSpan.FromSeconds(5));

            var success2 = await _client.UpdateRegistry(key.privateKey, key.publicKey, dataKey, "update2");

            await Task.Delay(TimeSpan.FromSeconds(5));

            var result = await _client.GetRegistry(key.publicKey, dataKey);

            Assert.IsTrue(success);
            Assert.IsTrue(success2);

            Assert.AreEqual("update2", result.GetDataAsString());
        }
Ejemplo n.º 18
0
        public async Task TestSkyDbUpdate()
        {
            RegistryKey dataKey = new RegistryKey("skydbtest-" + Guid.NewGuid());
            var         key     = SiaSkynetClient.GenerateKeys(_testSeed);

            var success = await _client.SkyDbSetAsString(key.privateKey, key.publicKey, dataKey, "update1");

            Assert.IsTrue(success);
            await Task.Delay(TimeSpan.FromSeconds(5));

            var success2 = await _client.SkyDbSetAsString(key.privateKey, key.publicKey, dataKey, "update2");

            await Task.Delay(TimeSpan.FromSeconds(5));

            string result = await _client.SkyDbGetAsString(key.publicKey, dataKey);

            Assert.IsTrue(success);
            Assert.IsTrue(success2);

            Assert.AreEqual("update2", result);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var sky = new SiaSkynetClient();
            //var upload = sky.UploadFileAsync("next.tar", File.OpenRead("next.tar"));
            //var skyResult = upload.GetAwaiter().GetResult();
            //Console.WriteLine(skyResult.Skylink);
            //Console.WriteLine(skyResult.Merkleroot);
            //Console.WriteLine(skyResult.Bitfield);

            //var download = sky.DownloadFileAsStringAsync("AAC0uO43g64ULpyrW0zO3bjEknSFbAhm8c-RFP21EQlmSQ");
            //Console.WriteLine(download.Result.file);

            var key   = SiaSkynetClient.GenerateKeys("milkey");
            var dbGet = sky.SkyDbGetAsString(key.publicKey, "blazor-sample");

            Console.WriteLine(dbGet.Result);

            var dbSet = sky.SkyDbSet(key.privateKey, key.publicKey, "blazor-sample", "hello");

            Console.WriteLine(dbSet.Result);
        }
Ejemplo n.º 20
0
        public void SetPortalDomain(string scheme, string domain)
        {
            //Do not use Internet Computer as domain for Sia Skynet calls
            if (domain.Contains("ic0.app", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            string[] urlParts = domain.Split('.');

            //Only take last two parts
            var lastParts = urlParts.Skip(urlParts.Count() - 2).Take(2);

            if (lastParts.Count() == 2)
            {
                var url = $"{scheme}://{string.Join('.', lastParts)}";
                Console.WriteLine($"Using API domain: {url}");

                var httpClient = httpClientFactory.CreateClient("API");
                client = new SiaSkynetClient(httpClient, url);
            }
        }
        public async Task TestSetRegistry_With_DiscoverableBucket()
        {
            var path    = $"crqa.hns/snew.hns/newcontent/{Guid.NewGuid().ToString()}/index.json";
            var bucket  = new DiscoverableBucket(path);
            var dataKey = new RegistryKey(bucket);

            int    revision = 0;
            string data     = "IADUs8d9CQjUO34LmdaaNPK_STuZo24rpKVfYW3wPPM2uQ"; //Sia logo

            var key = SiaSkynetClient.GenerateKeys(_testSeed);

            RegistryEntry reg = new RegistryEntry(dataKey);

            reg.SetData(data);
            reg.Revision = revision;

            var success = await _client.SetRegistry(key.privateKey, key.publicKey, reg);

            Assert.IsTrue(success);

            var result = await _client.GetRegistry(key.publicKey, dataKey);

            Assert.AreEqual(data, result.GetDataAsString());
        }
Ejemplo n.º 22
0
        public async Task <string> GetMessage([FromBody] GetMessageRequest req)
        {
            //Check hash
            var hashKey = SiaSkynetClient.GenerateKeys(req.Address);

            var cipherData = Utils.HexStringToByteArray(req.SecretHash);
            var decrypt    = Utils.Decrypt(cipherData, hashKey.privateKey);

            if (decrypt == null)
            {
                throw new Exception("Invalid hash.");
            }


            string address = req.Address.ToLowerInvariant();
            string seed    = $"{secretConfig.SkynetSeed}-{address}";
            var    key     = SiaSkynetClient.GenerateKeys(seed);

            var encryptedData = await client.DownloadFileAsByteArrayAsync(req.Skylink);

            var data = Utils.Decrypt(encryptedData.file, key.privateKey);

            return(Encoding.UTF8.GetString(data));
        }
Ejemplo n.º 23
0
        public CmsItemStorageService(IOptions <SkynetConfig> skynetConfig, IOptions <CmsConfiguration> cmsConfiguration)
        {
            this.skynetConfig     = skynetConfig.Value;
            this.cmsConfiguration = cmsConfiguration.Value;

            if (!string.IsNullOrEmpty(skynetConfig.Value.BaseUrl))
            {
                _client = new SiaSkynetClient(skynetConfig.Value.BaseUrl);
            }
            else
            {
                _client = new SiaSkynetClient();
            }

            if (string.IsNullOrWhiteSpace(this.skynetConfig.Secret))
            {
                throw new ArgumentNullException("SkynetConfig.Seed should contain a seed value to generate a private/public key pair.", nameof(skynetConfig));
            }

            var keypair = SiaSkynetClient.GenerateKeys(this.skynetConfig.Secret);

            privateKey = keypair.privateKey;
            publicKey  = keypair.publicKey;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Save document to SkyDB
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private async Task <bool> SaveDocument(Document doc, DocumentSummary sum)
        {
            //Only allowed to save if you have a private key for this document
            if (sum.PrivateKey == null)
            {
                return(false);
            }

            var  json    = JsonSerializer.Serialize(doc);
            bool success = false;

            try
            {
                if (IsDfinityNetwork || sum.StorageSource == StorageSource.Dfinity)
                {
                    await dfinityService.SetValue(doc.Id.ToString(), json);

                    success = true;
                }
                else
                {
                    //Encrypt with ContentSeed
                    var key           = SiaSkynetClient.GenerateKeys(sum.ContentSeed);
                    var data          = Encoding.UTF8.GetBytes(json);
                    var encryptedData = Utils.Encrypt(data, key.privateKey);

                    success = await client.SkyDbSet(sum.PrivateKey, sum.PublicKey, new RegistryKey(doc.Id.ToString()), encryptedData, doc.Revision + 1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }
            return(success);
        }
 public DiscoverableBucketTests()
 {
     _client = new SiaSkynetClient();
 }
Ejemplo n.º 26
0
 public RegistryTests()
 {
     _client = new SiaSkynetClient();
 }
Ejemplo n.º 27
0
 public void SetPortalDomain(string baseUrl)
 {
     client = new SiaSkynetClient(baseUrl);
 }
Ejemplo n.º 28
0
 public SkyfileTests()
 {
     _client = new SiaSkynetClient();
 }
Ejemplo n.º 29
0
 public ShareController(ILogger <ShareController> logger, IOptions <SecretConfig> secretConfig)
 {
     _logger           = logger;
     this.secretConfig = secretConfig.Value;
     client            = new SiaSkynetClient();
 }
Ejemplo n.º 30
0
 public ImageController(ILogger <ImageController> logger)
 {
     _logger = logger;
     client  = new SiaSkynetClient();
 }