本文整理汇总了C#中ByteString.ToByteArray方法的典型用法代码示例。如果您正苦于以下问题:C# ByteString.ToByteArray方法的具体用法?C# ByteString.ToByteArray怎么用?C# ByteString.ToByteArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ByteString
的用法示例。
在下文中一共展示了ByteString.ToByteArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetKeyStartingFrom
public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
{
byte[] from = prefix.ToByteArray();
byte[] to = prefix.ToByteArray();
to[to.Length - 1]++;
return await ExecuteQuery<Record>(
"EXEC [Openchain].[GetRecordRange] @instance, @from, @to;",
reader => new Record(new ByteString((byte[])reader[0]), new ByteString((byte[])reader[1]), new ByteString((byte[])reader[2])),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["from"] = from,
["to"] = to
});
}
示例2: PostTransaction
public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
{
Mutation mutation;
try
{
// Verify that the mutation can be deserialized
mutation = MessageSerializer.DeserializeMutation(rawMutation);
}
catch (InvalidProtocolBufferException)
{
throw new TransactionInvalidException("InvalidMutation");
}
if (!mutation.Namespace.Equals(this.ledgerId))
throw new TransactionInvalidException("InvalidNamespace");
if (mutation.Records.Count == 0)
throw new TransactionInvalidException("InvalidMutation");
if (mutation.Records.Any(record => record.Key.Value.Count > MaxKeySize))
throw new TransactionInvalidException("InvalidMutation");
ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));
ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);
// All assets must have an overall zero balance
IReadOnlyDictionary<AccountKey, AccountStatus> accounts =
await this.store.GetAccounts(parsedMutation.AccountMutations.Select(entry => entry.AccountKey));
var groups = parsedMutation.AccountMutations
.GroupBy(account => account.AccountKey.Asset.FullPath)
.Select(group => group.Sum(entry => entry.Balance - accounts[entry.AccountKey].Balance));
if (groups.Any(group => group != 0))
throw new TransactionInvalidException("UnbalancedTransaction");
DateTime date = DateTime.UtcNow;
await this.validator.Validate(parsedMutation, authentication, accounts);
TransactionMetadata metadata = new TransactionMetadata(authentication);
byte[] rawMetadata = SerializeMetadata(metadata);
Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);
try
{
await this.store.AddTransactions(new[] { new ByteString(serializedTransaction) });
}
catch (ConcurrentMutationException)
{
throw new TransactionInvalidException("OptimisticConcurrency");
}
return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
}
示例3: ToArray_Success
public void ToArray_Success()
{
byte[] sourceArray = new byte[] { 18, 178, 255, 70, 0 };
ByteString result = new ByteString(sourceArray);
Assert.Equal<byte>(new byte[] { 18, 178, 255, 70, 0 }, result.ToByteArray());
}
示例4: GetRecordMutations
public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
{
var key = recordKey.ToByteArray();
var res = await TransactionCollection.Find(Builders<MongoDbTransaction>.Filter.AnyEq(x=>x.Records, key))
.Project(x=>x.MutationHash)
.SortBy(x=>x.Timestamp)
.ToListAsync();
return res.Select(x=>new ByteString(x)).ToList().AsReadOnly();
}
示例5: ToData
/// <summary>
/// Converts a <see cref="ByteString"/> structure into a Helios <see cref="NetworkData"/> structure
/// </summary>
/// <param name="byteString">The data to send over the network</param>
/// <param name="address">The address that we received data from / are sending data to</param>
/// <returns>a new <see cref="NetworkData"/> struct</returns>
public static NetworkData ToData(ByteString byteString, Address address)
{
var data = new NetworkData()
{
Buffer = byteString.ToByteArray(),
RemoteHost = HeliosTransport.AddressToNode(address)
};
data.Length = data.Buffer.Length;
return data;
}
示例6: GetRecordMutations
public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
{
return await ExecuteQuery<ByteString>(
"EXEC [Openchain].[GetRecordMutations] @instance, @recordKey;",
reader => new ByteString((byte[])reader[0]),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["recordKey"] = recordKey.ToByteArray()
});
}
示例7: GetRecordMutations
public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
{
return await ExecuteAsync(@"
SELECT MutationHash
FROM RecordMutations
WHERE RecordKey = @recordKey",
reader => new ByteString((byte[])reader.GetValue(0)),
new Dictionary<string, object>()
{
["@recordKey"] = recordKey.ToByteArray()
});
}
示例8: GetPubKeyHash
public string GetPubKeyHash(ByteString pubKey)
{
Org.BouncyCastle.Crypto.Digests.RipeMD160Digest ripe = new Org.BouncyCastle.Crypto.Digests.RipeMD160Digest();
using (SHA256 sha256 = SHA256.Create())
{
byte[] shaResult = sha256.ComputeHash(pubKey.ToByteArray());
ripe.BlockUpdate(shaResult, 0, shaResult.Length);
byte[] hash = new byte[20];
ripe.DoFinal(hash, 0);
return Base58CheckEncoding.Encode(new byte[] { versionByte }.Concat(hash).ToArray());
}
}
示例9: GetKeyStartingFrom
public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
{
byte[] from = prefix.ToByteArray();
byte[] to = prefix.ToByteArray();
if (to[to.Length - 1] < 255)
to[to.Length - 1] += 1;
return await ExecuteAsync(@"
SELECT Key, Value, Version
FROM Records
WHERE Key >= @from AND Key < @to",
reader => new Record(
new ByteString((byte[])reader.GetValue(0)),
reader.GetValue(1) == null ? ByteString.Empty : new ByteString((byte[])reader.GetValue(1)),
new ByteString((byte[])reader.GetValue(2))),
new Dictionary<string, object>()
{
["@from"] = from,
["@to"] = to
});
}
示例10: GetKeyStartingFrom
public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
{
var prefixS = Encoding.UTF8.GetString(prefix.ToByteArray());
var list = new List<Record>();
var res = await RecordCollection.FindAsync(x => x.KeyS.StartsWith(prefixS));
await res.ForEachAsync(r =>
{
list.Add(new Record(new ByteString(r.Key), new ByteString(r.Value), new ByteString(r.Version)));
}
);
return list.AsReadOnly();
}
示例11: GetTransaction
public async Task<ByteString> GetTransaction(ByteString mutationHash)
{
IEnumerable<ByteString> transactions = await ExecuteAsync(@"
SELECT RawData
FROM Transactions
WHERE MutationHash = @mutationHash",
reader => new ByteString((byte[])reader.GetValue(0)),
new Dictionary<string, object>()
{
["@mutationHash"] = mutationHash.ToByteArray()
});
return transactions.FirstOrDefault();
}
示例12: Decode
/// <summary>
/// Decode a value of the given type.
/// Should not be called directly. This interface is used by service client stubs.
/// </summary>
public static object Decode(ByteString value, Type type, Connection client)
{
var stream = new CodedInputStream (value.ToByteArray ());
if (type == typeof(double))
return stream.ReadDouble ();
else if (type == typeof(float))
return stream.ReadFloat ();
else if (type == typeof(int))
return stream.ReadInt32 ();
else if (type == typeof(long))
return stream.ReadInt64 ();
else if (type == typeof(uint))
return stream.ReadUInt32 ();
else if (type == typeof(ulong))
return stream.ReadUInt64 ();
else if (type == typeof(bool))
return stream.ReadBool ();
else if (type == typeof(string))
return stream.ReadString ();
else if (type == typeof(byte[]))
return stream.ReadBytes ().ToByteArray ();
else if (type.IsEnum)
return stream.ReadInt32 ();
else if (typeof(RemoteObject).IsAssignableFrom (type)) {
if (client == null)
throw new ArgumentException ("Client not passed when decoding remote object");
var id = stream.ReadUInt64 ();
if (id == 0)
return null;
return (RemoteObject)Activator.CreateInstance (type, client, id);
} else if (typeof(IMessage).IsAssignableFrom (type)) {
IMessage message = (IMessage)Activator.CreateInstance (type);
message.MergeFrom (stream);
return message;
} else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IList<>))
return DecodeList (value, type, client);
else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IDictionary<,>))
return DecodeDictionary (value, type, client);
else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(ISet<>))
return DecodeSet (value, type, client);
else if (type.IsGenericType &&
(type.GetGenericTypeDefinition () == typeof(Tuple<>) ||
type.GetGenericTypeDefinition () == typeof(Tuple<,>) ||
type.GetGenericTypeDefinition () == typeof(Tuple<,,>) ||
type.GetGenericTypeDefinition () == typeof(Tuple<,,,>) ||
type.GetGenericTypeDefinition () == typeof(Tuple<,,,,>) ||
type.GetGenericTypeDefinition () == typeof(Tuple<,,,,,>)))
return DecodeTuple (value, type, client); // TODO: ugly handing of tuple types
throw new ArgumentException (type + " is not a serializable type");
}
示例13: PostTransaction
public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
{
Mutation mutation;
try
{
// Verify that the mutation can be deserialized
mutation = MessageSerializer.DeserializeMutation(rawMutation);
}
catch (InvalidProtocolBufferException)
{
throw new TransactionInvalidException("InvalidMutation");
}
ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);
IReadOnlyDictionary<AccountKey, AccountStatus> accounts = await ValidateMutation(mutation, parsedMutation);
ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));
DateTime date = DateTime.UtcNow;
IList<Mutation> generatedMutations = await this.validator.Validate(parsedMutation, authentication, accounts);
TransactionMetadata metadata = new TransactionMetadata(authentication);
byte[] rawMetadata = SerializeMetadata(metadata);
Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);
List<ByteString> transactions = new List<ByteString>() { new ByteString(serializedTransaction) };
transactions.AddRange(await Task.WhenAll(generatedMutations.Select(async generatedMutation =>
{
await ValidateMutation(generatedMutation, ParsedMutation.Parse(generatedMutation));
Transaction generatedTransaction = new Transaction(new ByteString(MessageSerializer.SerializeMutation(generatedMutation)), date, ByteString.Empty);
return new ByteString(MessageSerializer.SerializeTransaction(generatedTransaction));
})));
try
{
await this.store.AddTransactions(transactions);
}
catch (ConcurrentMutationException)
{
throw new TransactionInvalidException("OptimisticConcurrency");
}
return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
}
示例14: GetTransaction
public async Task<ByteString> GetTransaction(ByteString mutationHash)
{
IReadOnlyList<ByteString> result = await ExecuteQuery<ByteString>(
"EXEC [Openchain].[GetTransaction] @instance, @mutationHash;",
reader => new ByteString((byte[])reader[0]),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["mutationHash"] = mutationHash.ToByteArray()
});
if (result.Count > 0)
return result[0];
else
return null;
}
示例15: Subscribe
public async Task Subscribe(CancellationToken cancel)
{
byte[] buffer = new byte[1024 * 1024];
ArraySegment<byte> segment = new ArraySegment<byte>(buffer);
ByteString currentRecord = await this.store.GetLastTransaction();
while (!cancel.IsCancellationRequested)
{
try
{
ClientWebSocket socket = new ClientWebSocket();
this.endpoint.Query = string.Format("from={0}", currentRecord.ToString());
logger.LogInformation("Connecting to {0}", this.endpoint.Uri);
await socket.ConnectAsync(this.endpoint.Uri, cancel);
while (true)
{
WebSocketReceiveResult result = await socket.ReceiveAsync(segment, cancel);
if (result.MessageType == WebSocketMessageType.Close)
break;
ByteString record = new ByteString(buffer.Take(result.Count));
await store.AddTransactions(new[] { record });
currentRecord = new ByteString(MessageSerializer.ComputeHash(record.ToByteArray()));
}
}
catch (Exception exception)
{
logger.LogError("Error in the stream subscriber: {0}", exception.ToString());
}
await Task.Delay(TimeSpan.FromMinutes(1));
}
}