Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Back signature by Vector512 rather than byte[] #8008

Merged
merged 4 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Nethermind/Ethereum.Basic.Test/TransactionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void Test(TransactionTest test)

Transaction decodedSigned = Rlp.Decode<Transaction>(test.Signed);
ethereumEcdsa.Sign(test.PrivateKey, decodedUnsigned, false);
Assert.That(decodedUnsigned.Signature.R, Is.EqualTo(decodedSigned.Signature.R), "R");
Assert.That(decodedUnsigned.Signature.R.SequenceEqual(decodedSigned.Signature.R), "R");
BigInteger expectedS = decodedSigned.Signature.S.ToUnsignedBigInteger();
BigInteger actualS = decodedUnsigned.Signature.S.ToUnsignedBigInteger();
BigInteger otherS = EthereumEcdsa.LowSTransform - actualS;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public async Task Sign_SigningHash_RequestHasCorrectParameters()

var result = sut.Sign(Keccak.Zero);

Assert.That(new Signature(returnValue).Bytes, Is.EqualTo(result.Bytes));
Assert.That(new Signature(returnValue).Bytes.SequenceEqual(result.Bytes));
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public async Task Test_signing()
{
NullSigner signer = NullSigner.Instance;
await signer.Sign((Transaction)null!);
signer.Sign((Hash256)null!).Bytes.Should().HaveCount(64);
signer.Sign((Hash256)null!).Bytes.Length.Should().Be(64);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public async Task Test_signing()
{
Signer signer = new(1, TestItem.PrivateKeyA, LimboLogs.Instance);
await signer.Sign(Build.A.Transaction.TestObject);
signer.Sign(Keccak.Zero).Bytes.Should().HaveCount(64);
signer.Sign(Keccak.Zero).Bytes.Length.Should().Be(64);
}
}
}
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ public CliqueSealer(ISigner signer, ICliqueConfig config, ISnapshotManager snaps
}

// Copy signature bytes (R and S)
byte[] signatureBytes = signature.Bytes;
Array.Copy(signatureBytes, 0, header.ExtraData, header.ExtraData.Length - Clique.ExtraSealLength, signatureBytes.Length);
ReadOnlySpan<byte> signatureBytes = signature.Bytes;
signatureBytes.CopyTo(header.ExtraData.AsSpan(header.ExtraData.Length - Clique.ExtraSealLength));
// Copy signature's recovery id (V)
byte recoveryId = signature.RecoveryId;
header.ExtraData[^1] = recoveryId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void can_recover_from_message()
var signatureObject = new Signature(signatureSlice, recoveryId);
var keccak = Keccak.Compute(Bytes.Concat(messageType, data));
Span<byte> publicKey = stackalloc byte[65];
bool result = SpanSecP256k1.RecoverKeyFromCompact(publicKey, keccak.Bytes, signatureObject.Bytes, signatureObject.RecoveryId, false);
bool result = SpanSecP256k1.RecoverKeyFromCompact(publicKey, keccak.Bytes, signatureObject.Bytes.ToArray(), signatureObject.RecoveryId, false);
result.Should().BeTrue();
}
}
31 changes: 17 additions & 14 deletions src/Nethermind/Nethermind.Core/Crypto/Signature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using Nethermind.Core.Attributes;
using Nethermind.Core.Extensions;
using Nethermind.Int256;
Expand All @@ -12,38 +13,41 @@ namespace Nethermind.Core.Crypto
public class Signature : IEquatable<Signature>
{
public const int VOffset = 27;
private Vector512<byte> _signature;

public Signature(ReadOnlySpan<byte> bytes, int recoveryId)
{
ArgumentOutOfRangeException.ThrowIfNotEqual(bytes.Length, 64);

bytes.CopyTo(Bytes.AsSpan());
bytes.CopyTo(Bytes);
V = (ulong)recoveryId + VOffset;
}

public Signature(ReadOnlySpan<byte> bytes)
{
ArgumentOutOfRangeException.ThrowIfNotEqual(bytes.Length, 65);

bytes[..64].CopyTo(Bytes.AsSpan());
bytes[..64].CopyTo(Bytes);
V = bytes[64];
}

public Signature(ReadOnlySpan<byte> r, ReadOnlySpan<byte> s, ulong v)
{
ArgumentOutOfRangeException.ThrowIfLessThan(v, (ulong)VOffset);

r.CopyTo(Bytes.AsSpan(32 - r.Length, r.Length));
s.CopyTo(Bytes.AsSpan(64 - s.Length, s.Length));
Span<byte> span = Bytes;
r.CopyTo(span.Slice(32 - r.Length, r.Length));
s.CopyTo(span.Slice(64 - s.Length, s.Length));
V = v;
}

public Signature(in UInt256 r, in UInt256 s, ulong v)
{
ArgumentOutOfRangeException.ThrowIfLessThan(v, (ulong)VOffset);

r.ToBigEndian(Bytes.AsSpan(0, 32));
s.ToBigEndian(Bytes.AsSpan(32, 32));
Span<byte> span = Bytes;
r.ToBigEndian(span.Slice(0, 32));
s.ToBigEndian(span.Slice(32, 32));

V = v;
}
Expand All @@ -52,26 +56,25 @@ public Signature(string hexString)
: this(Core.Extensions.Bytes.FromHexString(hexString))
{
}

public byte[] Bytes { get; } = new byte[64];
public Span<byte> Bytes => MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref _signature, 1));
public ulong V { get; set; }

public ulong? ChainId => V < 35 ? null : (ulong?)(V + (V % 2) - 36) / 2;

public byte RecoveryId => V <= VOffset + 1 ? (byte)(V - VOffset) : (byte)(1 - V % 2);

public byte[] R => Bytes.Slice(0, 32);
public Span<byte> RAsSpan => Bytes.AsSpan(0, 32);
public byte[] S => Bytes.Slice(32, 32);
public Span<byte> SAsSpan => Bytes.AsSpan(32, 32);
public ReadOnlySpan<byte> R => Bytes.Slice(0, 32);
public ReadOnlySpan<byte> RAsSpan => Bytes.Slice(0, 32);
public ReadOnlySpan<byte> S => Bytes.Slice(32, 32);
public ReadOnlySpan<byte> SAsSpan => Bytes.Slice(32, 32);

[Todo("Change signature to store 65 bytes and just slice it for normal Bytes.")]
public byte[] BytesWithRecovery
{
get
{
var result = new byte[65];
Array.Copy(Bytes, result, 64);
Bytes.CopyTo(result);
result[64] = RecoveryId;
return result;
}
Expand All @@ -87,7 +90,7 @@ public bool Equals(Signature? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes) && V == other.V;
return _signature == other._signature && V == other.V;
}

public override bool Equals(object? obj)
Expand Down
8 changes: 8 additions & 0 deletions src/Nethermind/Nethermind.Core/Extensions/Bytes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,14 @@ public static byte[] Concat(byte[] bytes, byte suffix)
return result;
}

public static byte[] Concat(ReadOnlySpan<byte> bytes, byte suffix)
{
byte[] result = new byte[bytes.Length + 1];
result[^1] = suffix;
bytes.CopyTo(result);
return result;
}

public static byte[] Reverse(byte[] bytes)
{
byte[] result = new byte[bytes.Length];
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Core/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public string ToString(string indent)
builder.AppendLine($"{indent}Nonce: {Nonce}");
builder.AppendLine($"{indent}Value: {Value}");
builder.AppendLine($"{indent}Data: {(Data.AsArray() ?? []).ToHexString()}");
builder.AppendLine($"{indent}Signature: {(Signature?.Bytes ?? []).ToHexString()}");
builder.AppendLine($"{indent}Signature: {Signature?.Bytes.ToHexString()}");
builder.AppendLine($"{indent}V: {Signature?.V}");
builder.AppendLine($"{indent}ChainId: {Signature?.ChainId}");
builder.AppendLine($"{indent}Timestamp: {Timestamp}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,19 @@ public LegacyTransactionForRpc(Transaction transaction, int? txIndex = null, Has
GasPrice = transaction.GasPrice;
ChainId = transaction.ChainId;

R = new UInt256(transaction.Signature?.R ?? [], true);
S = new UInt256(transaction.Signature?.S ?? [], true);
V = transaction.Signature?.V ?? 0;
Signature? signature = transaction.Signature;
if (signature is null)
{
R = UInt256.Zero;
S = UInt256.Zero;
V = 0;
}
else
{
R = new UInt256(signature.R, true);
S = new UInt256(signature.S, true);
V = signature.V;
}
}

public override Transaction ToTransaction()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ protected static byte[] GenerateTransactionDataForEcRecover(Hash256 keccak, Sign
{
AbiDefinition call = new AbiDefinitionParser().Parse(GetEcRecoverContractJsonAbi(name));
AbiEncodingInfo functionInfo = call.GetFunction(name).GetCallInfo();
return AbiEncoder.Instance.Encode(functionInfo.EncodingStyle, functionInfo.Signature, keccak, signature.V, signature.R, signature.S);
return AbiEncoder.Instance.Encode(functionInfo.EncodingStyle, functionInfo.Signature, keccak, signature.V, signature.R.ToArray(), signature.S.ToArray());
benaadams marked this conversation as resolved.
Show resolved Hide resolved
}

private static Address? ParseEcRecoverAddress(byte[] data, string name = "recover")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public ResultWrapper<byte[]> eth_sign(Address addressData, byte[] message)
}

if (_logger.IsTrace) _logger.Trace($"eth_sign request {addressData}, {message}, result: {sig}");
return ResultWrapper<byte[]>.Success(sig.Bytes);
return ResultWrapper<byte[]>.Success(sig.Bytes.ToArray());
benaadams marked this conversation as resolved.
Show resolved Hide resolved
}

public virtual Task<ResultWrapper<Hash256>> eth_sendTransaction(TransactionForRpc rpcTx)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public ParityTransaction(Transaction transaction, byte[] raw, PublicKey publicKe
Input = transaction.Data.AsArray();
PublicKey = publicKey;
ChainId = transaction.Signature.ChainId;
R = transaction.Signature.R;
S = transaction.Signature.S;
R = transaction.Signature.R.ToArray();
S = transaction.Signature.S.ToArray();
benaadams marked this conversation as resolved.
Show resolved Hide resolved
V = (UInt256)transaction.Signature.V;
StandardV = transaction.Signature.RecoveryId;
// TKS: it does not seem to work with CREATE2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public ResultWrapper<byte[]> personal_sign(byte[] message, Address address, stri
}

message = ToEthSignedMessage(message);
return ResultWrapper<byte[]>.Success(_wallet.Sign(Keccak.Compute(message), address).Bytes);
return ResultWrapper<byte[]>.Success(_wallet.Sign(Keccak.Compute(message), address).Bytes.ToArray());
benaadams marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected void Serialize(byte type, Span<byte> data, IByteBuffer byteBuffer)

Signature signature = _ecdsa.Sign(_privateKey, toSign);
byteBuffer.SetWriterIndex(startWriteIndex + 32);
byteBuffer.WriteBytes(signature.Bytes, 0, 64);
byteBuffer.WriteBytes(signature.Bytes);
byteBuffer.WriteByte(signature.RecoveryId);

byteBuffer.SetReaderIndex(startReadIndex + 32);
Expand Down Expand Up @@ -76,7 +76,7 @@ protected void AddSignatureAndMdc(IByteBuffer byteBuffer, int dataLength)

Signature signature = _ecdsa.Sign(_privateKey, toSign);
byteBuffer.SetWriterIndex(startWriteIndex + 32);
byteBuffer.WriteBytes(signature.Bytes, 0, 64);
byteBuffer.WriteBytes(signature.Bytes);
byteBuffer.WriteByte(signature.RecoveryId);

byteBuffer.SetWriterIndex(startWriteIndex + length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ public void EncodeWithoutSignature(RlpStream stream, UInt256 chainId, Address co
private static int GetContentLength(AuthorizationTuple tuple) =>
GetContentLengthWithoutSig(tuple.ChainId, tuple.CodeAddress, tuple.Nonce)
+ Rlp.LengthOf(tuple.AuthoritySignature.V - Signature.VOffset)
+ Rlp.LengthOf(new UInt256(tuple.AuthoritySignature.R.AsSpan(), true))
+ Rlp.LengthOf(new UInt256(tuple.AuthoritySignature.S.AsSpan(), true));
+ Rlp.LengthOf(new UInt256(tuple.AuthoritySignature.R, true))
+ Rlp.LengthOf(new UInt256(tuple.AuthoritySignature.S, true));

private static int GetContentLengthWithoutSig(UInt256 chainId, Address codeAddress, ulong nonce) =>
Rlp.LengthOf(chainId)
Expand Down
Loading