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

add secp256k1 + keccak256 to signature verification. #3205

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
60 changes: 49 additions & 11 deletions src/Neo/Cryptography/Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public static class Crypto
private static readonly bool IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
private static readonly ECCurve secP256k1 = ECCurve.CreateFromFriendlyName("secP256k1");
private static readonly X9ECParameters bouncySecp256k1 = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
private static readonly X9ECParameters bouncySecp256r1 = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");

/// <summary>
/// Calculates the 160-bit hash value of the specified message.
Expand Down Expand Up @@ -55,17 +56,30 @@ public static byte[] Hash256(ReadOnlySpan<byte> message)
/// <param name="message">The message to be signed.</param>
/// <param name="priKey">The private key to be used.</param>
/// <param name="ecCurve">The <see cref="ECC.ECCurve"/> curve of the signature, default is <see cref="ECC.ECCurve.Secp256r1"/>.</param>
/// <param name="hasher">The hash algorithm of the signature, SHA256 by default</param>
/// <returns>The ECDSA signature for the specified message.</returns>
public static byte[] Sign(byte[] message, byte[] priKey, ECC.ECCurve ecCurve = null)
public static byte[] Sign(byte[] message, byte[] priKey, ECC.ECCurve ecCurve = null, Hasher hasher = Hasher.SHA256)
{
if (IsOSX && ecCurve == ECC.ECCurve.Secp256k1)
if (hasher == Hasher.Keccak256 || (IsOSX && ecCurve == ECC.ECCurve.Secp256k1))
{
var domain = new ECDomainParameters(bouncySecp256k1.Curve, bouncySecp256k1.G, bouncySecp256k1.N, bouncySecp256k1.H);
ECDomainParameters domain;
if (ecCurve == ECC.ECCurve.Secp256k1)
{
domain = new ECDomainParameters(bouncySecp256k1.Curve, bouncySecp256k1.G, bouncySecp256k1.N, bouncySecp256k1.H);
}
else if (ecCurve == ECC.ECCurve.Secp256r1)
{
domain = new ECDomainParameters(bouncySecp256r1.Curve, bouncySecp256r1.G, bouncySecp256r1.N, bouncySecp256r1.H);
}
else
{
throw new ArgumentException("Unsupported curve", nameof(ecCurve));
}
var signer = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner();
var privateKey = new BigInteger(1, priKey);
var priKeyParameters = new ECPrivateKeyParameters(privateKey, domain);
signer.Init(true, priKeyParameters);
var signature = signer.GenerateSignature(message.Sha256());
var signature = signer.GenerateSignature(hasher == Hasher.SHA256 ? message.Sha256() : message.Keccak256());

var signatureBytes = new byte[64];
var rBytes = signature[0].ToByteArrayUnsigned();
Expand Down Expand Up @@ -96,15 +110,33 @@ public static byte[] Sign(byte[] message, byte[] priKey, ECC.ECCurve ecCurve = n
/// <param name="message">The signed message.</param>
/// <param name="signature">The signature to be verified.</param>
/// <param name="pubkey">The public key to be used.</param>
/// <param name="hasher">The hash algorithm to be used.</param>
/// <returns><see langword="true"/> if the signature is valid; otherwise, <see langword="false"/>.</returns>
public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte> signature, ECC.ECPoint pubkey)
public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte> signature, ECC.ECPoint pubkey, Hasher hasher = Hasher.SHA256)
{
if (signature.Length != 64) return false;

if (IsOSX && pubkey.Curve == ECC.ECCurve.Secp256k1)
if (hasher == Hasher.Keccak256 || (IsOSX && pubkey.Curve == ECC.ECCurve.Secp256k1))
{
var domain = new ECDomainParameters(bouncySecp256k1.Curve, bouncySecp256k1.G, bouncySecp256k1.N, bouncySecp256k1.H);
var point = bouncySecp256k1.Curve.CreatePoint(
ECDomainParameters domain;
X9ECParameters curve;

if (pubkey.Curve == ECC.ECCurve.Secp256k1)
{
domain = new ECDomainParameters(bouncySecp256k1.Curve, bouncySecp256k1.G, bouncySecp256k1.N, bouncySecp256k1.H);
curve = bouncySecp256k1;
}
else if (pubkey.Curve == ECC.ECCurve.Secp256r1)
{
domain = new ECDomainParameters(bouncySecp256r1.Curve, bouncySecp256r1.G, bouncySecp256r1.N, bouncySecp256r1.H);
curve = bouncySecp256r1;
}
else
{
throw new ArgumentException("Unsupported curve", nameof(pubkey.Curve));
}

var point = curve.Curve.CreatePoint(
new BigInteger(pubkey.X.Value.ToString()),
new BigInteger(pubkey.Y.Value.ToString()));
var pubKey = new ECPublicKeyParameters("ECDSA", point, domain);
Expand All @@ -115,7 +147,12 @@ public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte
var r = new BigInteger(1, sig, 0, 32);
var s = new BigInteger(1, sig, 32, 32);

return signer.VerifySignature(message.Sha256(), r, s);
return hasher switch
{
Hasher.SHA256 => signer.VerifySignature(message.Sha256(), r, s),
Hasher.Keccak256 => signer.VerifySignature(message.Keccak256(), r, s),
_ => throw new ArgumentOutOfRangeException(nameof(hasher), hasher, "Invalid hasher")
};
}

var ecdsa = CreateECDsa(pubkey);
Expand Down Expand Up @@ -159,10 +196,11 @@ public static ECDsa CreateECDsa(ECC.ECPoint pubkey)
/// <param name="signature">The signature to be verified.</param>
/// <param name="pubkey">The public key to be used.</param>
/// <param name="curve">The curve to be used by the ECDSA algorithm.</param>
/// <param name="hasher">The hash algorithm to be used.</param>
/// <returns><see langword="true"/> if the signature is valid; otherwise, <see langword="false"/>.</returns>
public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte> signature, ReadOnlySpan<byte> pubkey, ECC.ECCurve curve)
public static bool VerifySignature(ReadOnlySpan<byte> message, ReadOnlySpan<byte> signature, ReadOnlySpan<byte> pubkey, ECC.ECCurve curve, Hasher hasher = Hasher.SHA256)
{
return VerifySignature(message, signature, ECC.ECPoint.DecodePoint(pubkey, curve));
return VerifySignature(message, signature, ECC.ECPoint.DecodePoint(pubkey, curve), hasher);
}
}
}
18 changes: 18 additions & 0 deletions src/Neo/Cryptography/Hasher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (C) 2015-2024 The Neo Project.
//
// Hasher.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.

namespace Neo.Cryptography;

public enum Hasher : byte
{
SHA256 = 0x00,
Keccak256 = 0x01,
}
20 changes: 20 additions & 0 deletions src/Neo/Cryptography/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Wallets;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
Expand Down Expand Up @@ -153,6 +154,25 @@ public static byte[] Sha256(this Span<byte> value)
return Sha256((ReadOnlySpan<byte>)value);
}

public static byte[] Keccak256(this byte[] value)
{
KeccakDigest keccak = new(256);
keccak.BlockUpdate(value, 0, value.Length);
byte[] result = new byte[keccak.GetDigestSize()];
keccak.DoFinal(result, 0);
return result;
}

public static byte[] Keccak256(this ReadOnlySpan<byte> value)
{
return Keccak256(value.ToArray());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return Keccak256(value.ToArray());
return Keccak256([.. value]);

}

public static byte[] Keccak256(this Span<byte> value)
{
return Keccak256(value.ToArray());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return Keccak256(value.ToArray());
return Keccak256([.. value]);

}

public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null)
{
if (nonce.Length != 12) throw new ArgumentOutOfRangeException(nameof(nonce));
Expand Down
16 changes: 8 additions & 8 deletions src/Neo/Network/P2P/Payloads/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -379,11 +379,11 @@
uint execFeeFactor = NativeContract.Policy.GetExecFeeFactor(snapshot);
for (int i = 0; i < hashes.Length; i++)
{
if (IsSignatureContract(witnesses[i].VerificationScript.Span))
net_fee -= execFeeFactor * SignatureContractCost();
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out int m, out int n))
if (IsSignatureContract(witnesses[i].VerificationScript.Span, out bool? isV2, out _, out _))
net_fee -= execFeeFactor * SignatureContractCost(isV2.Value);
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out int m, out int n, out isV2))
{
net_fee -= execFeeFactor * MultiSignatureContractCost(m, n);
net_fee -= execFeeFactor * MultiSignatureContractCost(m, n, isV2.Value);
}
else
{
Expand Down Expand Up @@ -415,21 +415,21 @@
UInt160[] hashes = GetScriptHashesForVerifying(null);
for (int i = 0; i < hashes.Length; i++)
{
if (IsSignatureContract(witnesses[i].VerificationScript.Span))
if (IsSignatureContract(witnesses[i].VerificationScript.Span, out bool? isV2, out ECCurve? curve, out Hasher? hasher))

Check warning on line 418 in src/Neo/Network/P2P/Payloads/Transaction.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 418 in src/Neo/Network/P2P/Payloads/Transaction.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 418 in src/Neo/Network/P2P/Payloads/Transaction.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dont add ? nullable until project is convert to nullable project.

{
if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid;
var pubkey = witnesses[i].VerificationScript.Span[2..35];
var pubkey = isV2.Value ? witnesses[i].VerificationScript.Span[4..37] : witnesses[i].VerificationScript.Span[2..35];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
var pubkey = isV2.Value ? witnesses[i].VerificationScript.Span[4..37] : witnesses[i].VerificationScript.Span[2..35];
var pubkey = isV2.Value ? witnesses[i].VerificationScript[4..37] : witnesses[i].VerificationScript[2..35];

try
{
if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript.Span[2..], pubkey, ECCurve.Secp256r1))
if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript.Span[2..], pubkey, curve, hasher.Value))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript.Span[2..], pubkey, curve, hasher.Value))
if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript[2..], pubkey, curve, hasher.Value))

return VerifyResult.InvalidSignature;
}
catch
{
return VerifyResult.Invalid;
}
}
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out var m, out ECPoint[] points))
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out var m, out ECPoint[] points, out isV2, out curve, out hasher))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
else if (IsMultiSigContract(witnesses[i].VerificationScript.Span, out var m, out ECPoint[] points, out isV2, out curve, out hasher))
else if (IsMultiSigContract(witnesses[i].VerificationScript, out var m, out ECPoint[] points, out isV2, out curve, out hasher))

{
if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid;
var signatures = GetMultiSignatures(witnesses[i].InvocationScript);
Expand Down
83 changes: 83 additions & 0 deletions src/Neo/SmartContract/ApplicationEngine.Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@
using Neo.Cryptography.ECC;
using Neo.Network.P2P;
using System;
using System.Collections.Generic;

namespace Neo.SmartContract
{
partial class ApplicationEngine
{
protected internal readonly static Dictionary<byte, ECCurve> ECCurveSelection = new(){
{ 0x00, ECCurve.Secp256r1 },
{ 0x01, ECCurve.Secp256k1 },
};

Comment on lines +22 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(This may not be the best place to put this dictionary)

/// <summary>
/// The price of System.Crypto.CheckSig.
/// </summary>
Expand All @@ -29,12 +35,24 @@ partial class ApplicationEngine
/// </summary>
public static readonly InteropDescriptor System_Crypto_CheckSig = Register("System.Crypto.CheckSig", nameof(CheckSig), CheckSigPrice, CallFlags.None);

/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Crypto.CheckSigV2.
/// Checks the signature (secp256k1, secp256r1, or other curve) for the current script container.
/// </summary>
public static readonly InteropDescriptor System_Crypto_CheckSigV2 = Register("System.Crypto.CheckSigV2", nameof(CheckSigV2), CheckSigPrice, CallFlags.None);

/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Crypto.CheckMultisig.
/// Checks the signatures for the current script container.
/// </summary>
public static readonly InteropDescriptor System_Crypto_CheckMultisig = Register("System.Crypto.CheckMultisig", nameof(CheckMultisig), 0, CallFlags.None);

/// <summary>
/// The <see cref="InteropDescriptor"/> of System.Crypto.CheckMultisigV2.
/// Checks the signatures (secp256k1, secp256r1, or other curve) for the current script container.
/// </summary>
public static readonly InteropDescriptor System_Crypto_CheckMultisigV2 = Register("System.Crypto.CheckMultisigV2", nameof(CheckMultisigV2), 0, CallFlags.None);

/// <summary>
/// The implementation of System.Crypto.CheckSig.
/// Checks the signature for the current script container.
Expand All @@ -54,6 +72,32 @@ protected internal bool CheckSig(byte[] pubkey, byte[] signature)
}
}

/// <summary>
/// This is a new version check signature method that allows for different curves and hashers.
/// </summary>
/// <param name="eccurve">The ec curve</param>
/// <param name="hash">The hash algorithm to get the hash of the message.</param>
/// <param name="pubkey">The public key.</param>
/// <param name="signature">The signature of the message.</param>
/// <returns>The signature is valid or not.</returns>
/// <exception cref="ArgumentOutOfRangeException">Throw if the given hash algorithm or ec curve is not defined.</exception>
protected internal bool CheckSigV2(byte eccurve, byte hash, byte[] pubkey, byte[] signature)
{
try
{
if (!Enum.IsDefined(typeof(Hasher), hash))
throw new ArgumentOutOfRangeException("Invalid hasher");
Hasher hasher = (Hasher)hash;
if (!ECCurveSelection.TryGetValue(eccurve, out ECCurve curve))
throw new ArgumentOutOfRangeException("Invalid EC curve");
return Crypto.VerifySignature(ScriptContainer.GetSignData(ProtocolSettings.Network), signature, pubkey, curve, hasher);
}
catch (Exception)
{
return false;
}
}

/// <summary>
/// The implementation of System.Crypto.CheckMultisig.
/// Checks the signatures for the current script container.
Expand Down Expand Up @@ -84,5 +128,44 @@ protected internal bool CheckMultisig(byte[][] pubkeys, byte[][] signatures)
}
return true;
}

/// <summary>
/// This is a new version check multisig method that allows for different curves and hashers.
/// </summary>
/// <param name="eccurve">The ec curve</param>
/// <param name="hash">The hash algorithm to get the hash of the message.</param>
/// <param name="pubkeys">The public keys.</param>
/// <param name="signatures">The signatures of the message.</param>
/// <returns>The signature is valid or not.</returns>
/// <exception cref="ArgumentOutOfRangeException">Throw if the given hash algorithm or ec curve is not defined.</exception>
protected internal bool CheckMultisigV2(byte eccurve, byte hash, byte[][] pubkeys, byte[][] signatures)
{
byte[] message = ScriptContainer.GetSignData(ProtocolSettings.Network);
int m = signatures.Length, n = pubkeys.Length;
if (n == 0 || m == 0 || m > n) throw new ArgumentException();
AddGas(CheckSigPrice * n * ExecFeeFactor);
try
{
if (!Enum.IsDefined(typeof(Hasher), hash))
throw new ArgumentOutOfRangeException("Invalid hasher");
Hasher hasher = (Hasher)hash;
if (!ECCurveSelection.TryGetValue(eccurve, out ECCurve curve))
throw new ArgumentOutOfRangeException("Invalid EC curve");

for (int i = 0, j = 0; i < m && j < n;)
{
if (Crypto.VerifySignature(message, signatures[i], pubkeys[j], curve, hasher))
i++;
j++;
if (m - i > n - j)
return false;
}
}
catch (ArgumentException)
{
return false;
}
return true;
}
}
}
Loading