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 5 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
39 changes: 32 additions & 7 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 @@ -96,15 +97,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 +134,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 +183,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 value.Keccak256();
}

public static byte[] Keccak256(this Span<byte> value)
{
return Keccak256((ReadOnlySpan<byte>)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
65 changes: 65 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 secp256k1 or other non-secp256r1 signature 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 secp256k1 or other non-secp256r1 signatures 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,23 @@ protected internal bool CheckSig(byte[] pubkey, byte[] signature)
}
}

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 +119,35 @@ protected internal bool CheckMultisig(byte[][] pubkeys, byte[][] signatures)
}
return true;
}

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;
}
}
}
6 changes: 1 addition & 5 deletions src/Neo/SmartContract/Native/CryptoLib.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,7 @@ public static byte[] Murmur32(byte[] data, uint seed)
[ContractMethod(Hardfork.HF_Cockatrice, CpuFee = 1 << 15)]
public static byte[] Keccak256(byte[] data)
{
KeccakDigest keccak = new(256);
keccak.BlockUpdate(data, 0, data.Length);
byte[] result = new byte[keccak.GetDigestSize()];
keccak.DoFinal(result, 0);
return result;
return data.Keccak256();
}

/// <summary>
Expand Down