public async Task GetMdInfoAsync() { try { // Retrieve MDataInfo from App container and deserialise var appContainerMDataInfo = await _session.AccessContainer.GetMDataInfoAsync("apps/" + Constants.AppId); var encryptedAppKey = await _session.MDataInfoActions.EncryptEntryKeyAsync(appContainerMDataInfo, AppContainerListKey.ToUtfBytes()); var encryptedValue = await _session.MData.GetValueAsync(appContainerMDataInfo, encryptedAppKey); if (encryptedValue.Item1 != null) { var plainValue = await _session.MDataInfoActions.DecryptAsync(appContainerMDataInfo, encryptedValue.Item1); _mDataInfo = await _session.MDataInfoActions.DeserialiseAsync(plainValue); } } catch (FfiException ex) { Debug.WriteLine("Error : " + ex.Message); await CreateMutableData(); await StoreMdInfoAsync(); } catch (Exception ex) { Debug.WriteLine("Error : " + ex.Message); throw; } }
private async Task GetMdInfoAsync() { try { var appContainerMDataInfo = await _session.AccessContainer.GetMDataInfoAsync("apps/" + AppId); var encrypedAppKey = await _session.MDataInfoActions.EncryptEntryKeyAsync(appContainerMDataInfo, mdByteList.ToUtfBytes()); (List <byte>, ulong)encryptedValue = await _session.MData.GetValueAsync(appContainerMDataInfo, encrypedAppKey); if (encryptedValue.Item1 != null) { var plainValue = await _session.MDataInfoActions.DecryptAsync(appContainerMDataInfo, encryptedValue.Item1); _mDataInfo = await _session.MDataInfoActions.DeserialiseAsync(plainValue); } } catch (FfiException ex) { Debug.WriteLine("Error : " + ex.Message); const ulong tagType = 16000; _mDataInfo = await _session.MDataInfoActions.RandomPrivateAsync(tagType); _newMdInfoFlag = true; } catch (Exception ex) { Debug.WriteLine("Error : " + ex.Message); throw ex; } _mDataAvailable = true; }
internal async Task CreateMutableData() { try { Console.WriteLine("\nCreating new mutable data"); const ulong tagType = 15010; _mdinfo = await _session.MDataInfoActions.RandomPrivateAsync(tagType); var mDataPermissionSet = new PermissionSet { Insert = true, ManagePermissions = true, Read = true, Update = true, Delete = true }; using (var permissionsH = await _session.MDataPermissions.NewAsync()) { using (var appSignKeyH = await _session.Crypto.AppPubSignKeyAsync()) { await _session.MDataPermissions.InsertAsync(permissionsH, appSignKeyH, mDataPermissionSet); await _session.MData.PutAsync(_mdinfo, permissionsH, NativeHandle.EmptyMDataEntries); } } Console.WriteLine("Mutable data created succesfully"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); Console.ReadLine(); Environment.Exit(1); } }
public MdDataOps(IMdNodeFactory nodeFactory, INetworkDataOps networkOps, MDataInfo mdInfo) { _mdInfo = mdInfo; _imDStore = new ImDStore(networkOps); Session = networkOps.Session; NodeFactory = nodeFactory; }
private async Task CreateMutableData() { // Create a new random private mutable data const ulong tagType = 16000; _mDataInfo = await _session.MDataInfoActions.RandomPrivateAsync(tagType); var mDataPermissionSet = new PermissionSet { Insert = true, ManagePermissions = true, Read = true, Update = true, Delete = true }; // Insert permission set using (var permissionsH = await _session.MDataPermissions.NewAsync()) { using (var appSignKeyH = await _session.Crypto.AppPubSignKeyAsync()) { await _session.MDataPermissions.InsertAsync(permissionsH, appSignKeyH, mDataPermissionSet); await _session.MData.PutAsync(_mDataInfo, permissionsH, NativeHandle.EmptyMDataEntries); } } }
public async Task UnregisteredRequestTest() { var someRandomSession = await Utils.CreateTestApp(); var publicMDataInfo = await Utils.PreparePublicDirectory(someRandomSession); someRandomSession.Dispose(); var uniqueId = Utils.GetRandomString(10); var(reqId, req) = await Session.EncodeUnregisteredRequestAsync(uniqueId); var response = await Utils.AuthenticateUnregisteredRequest(req); var ipcMsg = await Session.DecodeIpcMessageAsync(response); Assert.That(ipcMsg, Is.TypeOf <UnregisteredIpcMsg>()); var unregisteredClientResponse = ipcMsg as UnregisteredIpcMsg; Assert.That(unregisteredClientResponse, Is.Not.Null); Assert.That(unregisteredClientResponse.ReqId, Is.EqualTo(reqId)); var session = await Session.AppUnregisteredAsync(unregisteredClientResponse.SerialisedCfg); var mdInfo = new MDataInfo { Name = publicMDataInfo.Name, TypeTag = publicMDataInfo.TypeTag }; await session.MData.GetValueAsync(mdInfo, Encoding.UTF8.GetBytes("index.html").ToList()); session.Dispose(); }
/// <summary> /// Helper function to fetch the Container /// from a public ID and service name provided /// </summary> /// <param name="pubName">Requested public name</param> /// <param name="serviceName">Requested service name</param> /// <returns>MDataInfo for the service MData</returns> public async Task <MDataInfo> GetContainerFromPublicId(string pubName, string serviceName) { (List <byte>, ulong)serviceInfo; try { // Fetch mdata entry value for service var address = await SafeApp.Misc.Crypto.Sha3HashAsync(pubName.ToUtfBytes()); var servicesContainer = new MDataInfo { TypeTag = WebFetchConstants.DnsTagType, Name = address.ToArray() }; serviceInfo = await _session.MData.GetValueAsync( servicesContainer, (string.IsNullOrWhiteSpace(serviceName) ? WebFetchConstants.DefaultService : serviceName).ToUtfBytes()); } catch (FfiException ex) { Logger.Error(ex); switch (ex.ErrorCode) { // there is no container stored at the location case WebFetchConstants.NoSuchData: throw new WebFetchException(WebFetchConstants.NoSuchData, WebFetchConstants.NoSuchDataMessage); case WebFetchConstants.NoSuchEntry: throw new WebFetchException(WebFetchConstants.NoSuchEntry, WebFetchConstants.NoSuchEntryMessage); default: throw; } } // the matching service name was soft-deleted if (serviceInfo.Item1.Count == 0) { throw new WebFetchException(WebFetchConstants.ServiceNotFound, WebFetchConstants.ServiceNotFoundMessage); } // Try parsing the serive mdinfo MDataInfo serviceMd; try { serviceMd = await _session.MDataInfoActions.DeserialiseAsync(serviceInfo.Item1); } catch (Exception ex) { Logger.Error(ex); serviceMd = new MDataInfo { TypeTag = WebFetchConstants.WwwTagType, Name = serviceInfo.Item1.ToArray() }; } return(serviceMd); }
/// <summary> /// Open a file for reading or writing. /// </summary> /// <param name="mDataInfo">MDataInfo to access mutable data.</param> /// <param name="file">The file to be opened.</param> /// <param name="openMode">File opening Mode.</param> /// <returns></returns> public async Task <NativeHandle> FileOpenAsync(MDataInfo mDataInfo, File file, OpenMode openMode) { var fileContextHandle = await AppBindings.FileOpenAsync(_appPtr, ref mDataInfo, ref file, (ulong)openMode); return(new NativeHandle( _appPtr, fileContextHandle, handle => { return openMode == OpenMode.Read ? AppBindings.FileCloseAsync(_appPtr, handle) : Task.Run(() => { }); })); }
public async Task RandomPrivateMutableDataUpdateAction() { Utils.InitialiseSessionForRandomTestApp(); const ulong tagType = 15001; const string actKey = "sample_key"; const string actValue = "sample_value"; using (var mdInfoHandle = await MDataInfo.RandomPrivateAsync(tagType)) { using (var permissionSetH = await MDataPermissionSet.NewAsync()) { await MDataPermissionSet.AllowAsync(permissionSetH, MDataAction.Insert); await MDataPermissionSet.AllowAsync(permissionSetH, MDataAction.ManagePermissions); using (var permissionsH = await MDataPermissions.NewAsync()) { using (var appSignKeyH = await Crypto.AppPubSignKeyAsync()) { await MDataPermissions.InsertAsync(permissionsH, appSignKeyH, permissionSetH); await MData.MData.PutAsync(mdInfoHandle, permissionsH, NativeHandle.Zero); } } } using (var entryActionsH = await MDataEntryActions.NewAsync()) { var key = Encoding.Default.GetBytes(actKey).ToList(); var value = Encoding.Default.GetBytes(actValue).ToList(); key = await MDataInfo.EncryptEntryKeyAsync(mdInfoHandle, key); value = await MDataInfo.EncryptEntryValueAsync(mdInfoHandle, value); await MDataEntryActions.InsertAsync(entryActionsH, key, value); await MData.MData.MutateEntriesAsync(mdInfoHandle, entryActionsH); } using (var keysHandle = await MData.MData.ListKeysAsync(mdInfoHandle)) { var len = await MDataKeys.LenAsync(keysHandle); Assert.AreEqual(1, len.ToInt32()); } using (var entriesHandle = await MData.MData.ListEntriesAsync(mdInfoHandle)) { var entries = await MDataEntries.ForEachAsync(entriesHandle); Assert.AreEqual(1, entries.Count); var entry = entries.First(); var key = await MDataInfo.DecryptAsync(mdInfoHandle, entry.Item1); var value = await MDataInfo.DecryptAsync(mdInfoHandle, entry.Item2); var encoding = new ASCIIEncoding(); Assert.AreEqual(actKey, encoding.GetString(key.ToArray())); Assert.AreEqual(actValue, encoding.GetString(value.ToArray())); } } }
async Task AddObjectAsync(MDataInfo md, string key, object value) { using (var entryActionsH = await _session.MDataEntryActions.NewAsync().ConfigureAwait(false)) { // insert value var insertObj = new Dictionary <string, object> { { key, value } }; await _networkOps.InsertEntriesAsync(entryActionsH, insertObj).ConfigureAwait(false); // commit await _networkOps.CommitEntryMutationAsync(md, entryActionsH).ConfigureAwait(false); } }
public async Task PrivateMd_IsNOTFound_When_TagType_IsNotSame() { var(xor, tag) = await MdLocator(_session); var dstPubIdMDataInfoH = new MDataInfo { Name = xor, TypeTag = 15001 }; try { var keys = await _session.MData.ListKeysAsync(dstPubIdMDataInfoH); Assert.Fail(); } catch (Exception ex) { } }
public async Task <MDataInfo> GetAccessContainerMdataInfoAsync() { try { _accessContainerMdinfo = await _session.AccessContainer.GetMDataInfoAsync($"apps/{Constants.AppId}"); } catch (FfiException ex) { Logger.Error(ex); } catch (Exception ex) { Logger.Error(ex); throw; } return(_accessContainerMdinfo); }
public async Task <Result <MDataInfo> > LocatePublicMd(byte[] xor, ulong protocol) { var md = new MDataInfo { Name = xor, TypeTag = protocol }; try { await Session.MData.ListKeysAsync(md); } catch { // (System.Exception ex) return(new KeyNotFound <MDataInfo>($"Could not find Md with tag type {protocol} and address {xor}")); } return(Result.OK(md)); }
public async Task PublicMd_IsNOTFound_When_TagType_IsNotSame() { var(xor, _) = await MdLocator(_session, pub : true); var dstPubIdMDataInfoH = new MDataInfo { Name = xor, TypeTag = 15001 }; try { var keys = await _session.MData.ListKeysAsync(dstPubIdMDataInfoH); Assert.Fail(); } catch { } }
public async Task PublicMd_IsFound_When_TagType_IsSame() { var(xor, tag) = await MdLocator(_session, pub : true); var dstPubIdMDataInfoH = new MDataInfo { Name = xor, TypeTag = tag }; try { var keys = await _session.MData.ListKeysAsync(dstPubIdMDataInfoH); Assert.IsNotNull(keys); } catch (Exception ex) { Assert.Fail(); } }
/// <summary> /// Helper function to read the file's content, and return an /// http compliant response based on the mime-type and options provided /// </summary> /// <param name="fileMdInfo">Opened file's MdInfo</param> /// <param name="openedFile">Open file</param> /// <param name="options">WebFetch options (ex. range to read)</param> /// <returns>Data as List < byte >, startIndex, endIndex, and size</returns> public async Task <(List <byte>, ulong, ulong, ulong)> ReadContentFromFile( MDataInfo fileMdInfo, WebFile openedFile, WebFetchOptions options = null) { try { var fileHandle = await _session.NFS.FileOpenAsync(fileMdInfo, openedFile.File, SafeApp.Misc.NFS.OpenMode.Read); var fileSize = await _session.NFS.FileSizeAsync(fileHandle); if (options == null) { var fileData = await _session.NFS.FileReadAsync(fileHandle, 0, fileSize - 1); return(fileData, 0, fileSize - 1, fileSize); } else { var partStartIndex = options.Range[0].Start > 0 ? options.Range[0].Start : 0; ulong partEndIndex; if (options.Range[0].End > 0) { partEndIndex = options.Range[0].End; } else { partEndIndex = fileSize - 1; } var partSize = partEndIndex - partStartIndex + 1; var fileData = await _session.NFS.FileReadAsync(fileHandle, partStartIndex, partSize); return(fileData, partStartIndex, partEndIndex, partSize); } } catch (Exception ex) { Logger.Error(ex); } return(null, 0, 0, 0); }
public async Task RandomPublicMutableDataInsertAction() { Utils.InitialiseSessionForRandomTestApp(); const ulong tagType = 15001; using (var mdInfoHandle = await MDataInfo.RandomPublicAsync(tagType)) { using (var permissionSetH = await MDataPermissionSet.NewAsync()) { await MDataPermissionSet.AllowAsync(permissionSetH, MDataAction.Insert); await MDataPermissionSet.AllowAsync(permissionSetH, MDataAction.ManagePermissions); using (var permissionsH = await MDataPermissions.NewAsync()) { using (var appSignKeyH = await Crypto.AppPubSignKeyAsync()) { await MDataPermissions.InsertAsync(permissionsH, appSignKeyH, permissionSetH); await MData.MData.PutAsync(mdInfoHandle, permissionsH, NativeHandle.Zero); } } } using (var entryActionsH = await MDataEntryActions.NewAsync()) { var key = Encoding.Default.GetBytes("sample_key").ToList(); var value = Encoding.Default.GetBytes("sample_value").ToList(); await MDataEntryActions.InsertAsync(entryActionsH, key, value); await MData.MData.MutateEntriesAsync(mdInfoHandle, entryActionsH); } using (var entryActionsH = await MDataEntryActions.NewAsync()) { var key = Encoding.Default.GetBytes("sample_key_2").ToList(); var value = Encoding.Default.GetBytes("sample_value_2").ToList(); await MDataEntryActions.InsertAsync(entryActionsH, key, value); await MData.MData.MutateEntriesAsync(mdInfoHandle, entryActionsH); } using (var keysHandle = await MData.MData.ListKeysAsync(mdInfoHandle)) { var len = await MDataKeys.LenAsync(keysHandle); Assert.AreEqual(2, len.ToInt32()); } } }
private static async Task CreateMutableData() { const ulong tagType = 15010; _mdinfo = await _session.MDataInfoActions.RandomPublicAsync(tagType); var mDataPermissionSet = new PermissionSet { Insert = true, ManagePermissions = true, Read = true, Update = true, Delete = true }; using (var permissionsH = await _session.MDataPermissions.NewAsync()) { using (var appSignKeyH = await _session.Crypto.AppPubSignKeyAsync()) { await _session.MDataPermissions.InsertAsync(permissionsH, appSignKeyH, mDataPermissionSet); await _session.MData.PutAsync(_mdinfo, permissionsH, NativeHandle.Zero); } } }
public async Task <Result <MDataInfo> > LocatePrivateMd(byte[] xor, ulong protocol, byte[] secEncKey, byte[] nonce) { var md = new MDataInfo { Name = xor, TypeTag = protocol }; try { await Session.MData.ListKeysAsync(md); } catch { // (System.Exception ex) return(new KeyNotFound <MDataInfo>($"Could not find Md with tag type {protocol} and address {xor}")); } md = await Session.MDataInfoActions.NewPrivateAsync(xor, protocol, secEncKey, nonce); return(Result.OK(md)); }
async Task NewMetadata(MDataInfo md) { var keys = await _session.MData.ListKeysAsync(md).ConfigureAwait(false); if (keys.Count > 0) { var metaMD = await _session.MData.GetValueAsync(md, METADATA_KEY_BYTES).ConfigureAwait(false); var level = metaMD.Item1.ToUtfString().Parse <int>(); return; } var insertObj = new Dictionary <string, object> { { METADATA_KEY, 0 } }; using (var entryActionsH = await _session.MDataEntryActions.NewAsync().ConfigureAwait(false)) { await _networkOps.InsertEntriesAsync(entryActionsH, insertObj).ConfigureAwait(false); await _networkOps.CommitEntryMutationAsync(md, entryActionsH).ConfigureAwait(false); } }
public MdOps(MDataInfo mdInfo, Session session) : base(session) { _mdInfo = mdInfo; }
public void SetMdInfo(MDataInfo mdinfo) { _accesscontainerMdinfo = mdinfo; }
/// <summary> /// Delete a file from path. /// Directly commit to the network. /// </summary> /// <param name="mDataInfo">mdataInfo to access Mutable Data.</param> /// <param name="fileName">The path/file name.</param> /// <param name="version">The version successor, to handle the concurrency issue.</param> /// <returns>The version successor for the deleted file.</returns> public Task <ulong> DirDeleteFileAsync(MDataInfo mDataInfo, string fileName, ulong version) { return(AppBindings.DirDeleteFileAsync(_appPtr, ref mDataInfo, fileName, version)); }
/// <summary> /// Helper function to try private different paths private to find and /// fetch the index file from a web site container. /// </summary> /// <param name="fileMdInfo">File MdInfo</param> /// <param name="initialPath">Path</param> /// <returns>WebFile</returns> public async Task <WebFile> TryDifferentPaths(MDataInfo fileMdInfo, string initialPath) { void HandleNfsFetchException(FfiException exception) { Logger.Error(exception); if (exception.ErrorCode != WebFetchConstants.FileNotFound) { throw exception; } } File?file = null; var filePath = string.Empty; try { filePath = initialPath; (file, _) = await _session.NFS.DirFetchFileAsync(fileMdInfo, filePath); } catch (Exception ex) { if (ex.GetType() == typeof(FfiException)) { HandleNfsFetchException((FfiException)ex); } } if (file == null && initialPath.StartsWith("/")) { try { filePath = initialPath.Substring(1, initialPath.Length - 1); (file, _) = await _session.NFS.DirFetchFileAsync(fileMdInfo, filePath); } catch (Exception ex) { if (ex.GetType() == typeof(FfiException)) { HandleNfsFetchException((FfiException)ex); } } } if (file == null && initialPath.StartsWith("/")) { try { filePath = $"{initialPath}/{WebFetchConstants.IndexFileName}"; (file, _) = await _session.NFS.DirFetchFileAsync(fileMdInfo, filePath); } catch (Exception ex) { if (ex.GetType() == typeof(FfiException)) { HandleNfsFetchException((FfiException)ex); } } } if (file == null) { try { filePath = $"{initialPath}/{WebFetchConstants.IndexFileName}"; filePath = filePath.Substring(1, filePath.Length - 1); (file, _) = await _session.NFS.DirFetchFileAsync(fileMdInfo, filePath); } catch (Exception ex) { if (ex.GetType() == typeof(FfiException)) { HandleNfsFetchException((FfiException)ex); } throw new WebFetchException(WebFetchConstants.FileNotFound, WebFetchConstants.FileNotFoundMessage); } } var extension = filePath.Substring(filePath.LastIndexOf('.') + 1); var mimeType = MimeUtility.GetMimeMapping(extension); return(new WebFile { File = file.Value, MimeType = mimeType }); }
public MdDataOps(Session session, MDataInfo mdInfo) { Session = session; _mdInfo = mdInfo; }
public MdNode(MDataInfo mdInfo, Session session) { _mdInfo = mdInfo; _dataOps = new MdDataOps(session, mdInfo); }
/// <summary> /// Replace the existing file with a new file. /// Directly commit to the network. /// </summary> /// <param name="mDataInfo">MDataInfo to access mutable data.</param> /// <param name="fileName">The path to store the file under.</param> /// <param name="file">The file to Serialise and store.</param> /// <param name="version">Version successor, to handle the concurrency issue.</param> /// <returns></returns> public Task DirUpdateFileAsync(MDataInfo mDataInfo, string fileName, File file, ulong version) { return(AppBindings.DirUpdateFileAsync(_appPtr, ref mDataInfo, fileName, ref file, version)); }
/// <summary> /// Insert the given file in the directory. /// Directly commit to the network. /// </summary> /// <param name="mDataInfo">MDataInfo to access mutable data.</param> /// <param name="fileName">The path to store the file under.</param> /// <param name="file">The file to Serialise and store.</param> /// <returns></returns> public Task DirInsertFileAsync(MDataInfo mDataInfo, string fileName, File file) { return(AppBindings.DirInsertFileAsync(_appPtr, ref mDataInfo, fileName, ref file)); }
/// <summary> /// Get the file from the directory. /// </summary> /// <param name="mDataInfo">MDataInfo to access mutable data.</param> /// <param name="fileName">The path/file name.</param> /// <returns>The file found for the given path.</returns> public Task <(File, ulong)> DirFetchFileAsync(MDataInfo mDataInfo, string fileName) { return(AppBindings.DirFetchFileAsync(_appPtr, ref mDataInfo, fileName)); }
// Creates db with address to category MD public async Task CreateDbAsync(string databaseId) { databaseId = DbIdForProtocol(databaseId); if (databaseId.Contains(".") || databaseId.Contains("@")) { throw new NotSupportedException("Unsupported characters '.' and '@'."); } // Check if account exits first and return error var dstPubIdDigest = await GetMdXorName(databaseId); var pubKey = await _crypto.AppPubEncKeyAsync(); var dstPubIdMDataInfoH = new MDataInfo { Name = dstPubIdDigest.ToArray(), TypeTag = 15001 }; var accountExists = false; try { await _mData.ListKeysAsync(dstPubIdMDataInfoH); accountExists = true; } catch (Exception) { // ignored - acct not found } if (accountExists) { throw new Exception("Id already exists."); } var permissions = new PermissionSet { Delete = true, Insert = true, ManagePermissions = true, Read = true, Update = true }; // Create Self Permissions using (var streamTypesPermH = await _mDataPermissions.NewAsync()) { using (var appSignPkH = await _crypto.AppPubSignKeyAsync()) { await _mDataPermissions.InsertAsync(streamTypesPermH, appSignPkH, permissions); } // Create Md for holding categories var categoriesMDataInfoH = await _mDataInfo.RandomPrivateAsync(15001); await _mData.PutAsync(categoriesMDataInfoH, streamTypesPermH, NativeHandle.Zero); // <---------------------------------------------- Commit ------------------------ var serializedCategoriesMdInfo = await _mDataInfo.SerialiseAsync(categoriesMDataInfoH); // Finally update App Container (store db info to it) var database = new Database { DbId = databaseId, Categories = new DataArray { Type = "Buffer", Data = serializedCategoriesMdInfo }, // Points to Md holding stream types //Archive = new DataArray {Type = "Buffer", Data = serializedDatabaseMdInfo}, //DataEncPk = categoryEncPk.ToHexString(), //DataEncSk = categoryEncSk.ToHexString() }; var serializedDb = JsonConvert.SerializeObject(database); var appContH = await _accessContainer.GetMDataInfoAsync(AppContainerPath); // appContainerHandle var dbIdCipherBytes = await _mDataInfo.EncryptEntryKeyAsync(appContH, database.DbId.ToUtfBytes()); var dbCipherBytes = await _mDataInfo.EncryptEntryValueAsync(appContH, serializedDb.ToUtfBytes()); using (var appContEntryActionsH = await _mDataEntryActions.NewAsync()) { await _mDataEntryActions.InsertAsync(appContEntryActionsH, dbIdCipherBytes, dbCipherBytes); await _mData.MutateEntriesAsync(appContH, appContEntryActionsH); // <---------------------------------------------- Commit ------------------------ } } }