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

Implement NotaryAssisted transaction attribute #3175

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
6da4ae2
Implement NotaryAssisted transaction attribute
AnnaShaleva Mar 6, 2024
acec1b0
Payloads: add doc to CalculateNetworkFee method of NotaryAssisted att…
AnnaShaleva Mar 6, 2024
1508d4f
Native: add NotaryAssisted attributes handler to Gas OnPersist
AnnaShaleva Mar 7, 2024
8b547c9
Payloads: adjust comment to NotaryAssisted attribute
AnnaShaleva Mar 7, 2024
b16a28c
Payloads: temporary use hard-coded Notary contract hash
AnnaShaleva Mar 7, 2024
00b54ff
Merge branch 'master' into notary-assisted
Jim8y Mar 8, 2024
24135ff
Payloads: replace hard-coded Notary hash value with calculated one
AnnaShaleva Mar 12, 2024
2fb879d
Merge branch 'master' into notary-assisted
shargon Apr 2, 2024
a260253
Merge branch 'master' into notary-assisted
shargon Apr 9, 2024
e2f0360
Merge branch 'master' into notary-assisted
cschuchardt88 May 23, 2024
fbf5eae
NeoModules: integrate NotaryAssisted attribute
AnnaShaleva Jun 5, 2024
151f859
Payloads: fix XML comment formatting
AnnaShaleva Jun 10, 2024
042440f
Merge branch 'master' into notary-assisted
AnnaShaleva Jun 11, 2024
c229cd5
P2P: move NotaryAssisted transaction attribute under D hardfork
AnnaShaleva Jun 11, 2024
01ddf78
Merge branch 'master' into notary-assisted
AnnaShaleva Jun 24, 2024
4d5cee9
P2P: move NotaryAssisted transaction attribute under E hardfork
AnnaShaleva Jun 24, 2024
53a031d
Merge branch 'master' into notary-assisted
AnnaShaleva Jan 16, 2025
8e33ca4
tests: fix build errors
AnnaShaleva Jan 16, 2025
08a41ce
NotaryAssisted: update copyright date
AnnaShaleva Jan 16, 2025
0d3012e
Merge branch 'master' into notary-assisted
AnnaShaleva Jan 17, 2025
ab422d7
Merge branch 'master' into notary-assisted
cschuchardt88 Jan 17, 2025
4af93c8
Merge branch 'master' into notary-assisted
AnnaShaleva Jan 23, 2025
ec4e3d6
SmartContract: refactor obsolete code
AnnaShaleva Jan 23, 2025
bf4b294
Persistance: fix UT
AnnaShaleva Jan 23, 2025
d5f37df
Clean comments
shargon Jan 23, 2025
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
4 changes: 4 additions & 0 deletions src/Neo.CLI/CLI/MainService.Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@ public void OnShowTransactionCommand(UInt256 hash)
ConsoleHelper.Info("", " Type: ", $"{n.Type}");
ConsoleHelper.Info("", " Height: ", $"{n.Height}");
break;
case NotaryAssisted n:
ConsoleHelper.Info("", " Type: ", $"{n.Type}");
ConsoleHelper.Info("", " NKeys: ", $"{n.NKeys}");
break;
default:
ConsoleHelper.Info("", " Type: ", $"{attribute.Type}");
ConsoleHelper.Info("", " Size: ", $"{attribute.Size} Byte(s)");
Expand Down
76 changes: 76 additions & 0 deletions src/Neo/Network/P2P/Payloads/NotaryAssisted.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// NotaryAssisted.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.

using Neo.IO;
using Neo.Json;
using Neo.Persistence;
using Neo.SmartContract.Native;
using System.IO;
using System.Linq;

namespace Neo.Network.P2P.Payloads
{
public class NotaryAssisted : TransactionAttribute
{
/// <summary>
/// Native Notary contract hash stub used until native Notary contract is properly implemented.
/// </summary>
private static readonly UInt160 notaryHash = Neo.SmartContract.Helper.GetContractHash(UInt160.Zero, 0, "Notary");

/// <summary>
/// Indicates the number of keys participating in the transaction (main or fallback) signing process.
/// </summary>
public byte NKeys;

public override TransactionAttributeType Type => TransactionAttributeType.NotaryAssisted;

public override bool AllowMultiple => false;

public override int Size => base.Size + sizeof(byte);

protected override void DeserializeWithoutType(ref MemoryReader reader)
{
NKeys = reader.ReadByte();
}

protected override void SerializeWithoutType(BinaryWriter writer)
{
writer.Write(NKeys);
}

public override JObject ToJson()
{
JObject json = base.ToJson();
json["nkeys"] = NKeys;
return json;
}

public override bool Verify(DataCache snapshot, Transaction tx)
AnnaShaleva marked this conversation as resolved.
Show resolved Hide resolved
{
return tx.Signers.Any(p => p.Account.Equals(notaryHash));
}

/// <summary>
/// Calculates the network fee needed to pay for NotaryAssisted attribute. According to the
/// https://github.com/neo-project/neo/issues/1573#issuecomment-704874472, network fee consists of
/// the base Notary service fee per key multiplied by the expected number of transactions that should
/// be collected by the service to complete Notary request increased by one (for Notary node witness
/// itself).
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="tx">The transaction to calculate.</param>
/// <returns>The network fee of the NotaryAssisted attribute.</returns>
public override long CalculateNetworkFee(DataCache snapshot, Transaction tx)
{
return (NKeys + 1) * base.CalculateNetworkFee(snapshot, tx);
}
}
}
7 changes: 5 additions & 2 deletions src/Neo/Network/P2P/Payloads/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -376,10 +376,13 @@ public virtual VerifyResult VerifyStateDependent(ProtocolSettings settings, Data
if (!(context?.CheckTransaction(this, conflictsList, snapshot) ?? true)) return VerifyResult.InsufficientFunds;
long attributesFee = 0;
foreach (TransactionAttribute attribute in Attributes)
{
if (attribute.Type == TransactionAttributeType.NotaryAssisted && !settings.IsHardforkEnabled(Hardfork.HF_Echidna, height))
return VerifyResult.InvalidAttribute;
if (!attribute.Verify(snapshot, this))
return VerifyResult.InvalidAttribute;
else
attributesFee += attribute.CalculateNetworkFee(snapshot, this);
attributesFee += attribute.CalculateNetworkFee(snapshot, this);
}
long netFeeDatoshi = NetworkFee - (Size * NativeContract.Policy.GetFeePerByte(snapshot)) - attributesFee;
if (netFeeDatoshi < 0) return VerifyResult.InsufficientFunds;

Expand Down
8 changes: 7 additions & 1 deletion src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public enum TransactionAttributeType : byte
/// Indicates that the transaction conflicts with <see cref="Conflicts.Hash"/>.
/// </summary>
[ReflectionCache(typeof(Conflicts))]
Conflicts = 0x21
Conflicts = 0x21,

/// <summary>
/// Indicates that the transaction uses notary request service with <see cref="NotaryAssisted.NKeys"/> number of keys.
/// </summary>
[ReflectionCache(typeof(NotaryAssisted))]
NotaryAssisted = 0x22
}
}
8 changes: 8 additions & 0 deletions src/Neo/SmartContract/Native/GasToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ internal override async ContractTask OnPersistAsync(ApplicationEngine engine)
{
await Burn(engine, tx.Sender, tx.SystemFee + tx.NetworkFee);
totalNetworkFee += tx.NetworkFee;

// Reward for NotaryAssisted attribute will be minted to designated notary nodes
// by Notary contract.
var notaryAssisted = tx.GetAttribute<NotaryAssisted>();
if (notaryAssisted is not null)
{
totalNetworkFee -= (notaryAssisted.NKeys + 1) * Policy.GetAttributeFee(engine.SnapshotCache, (byte)notaryAssisted.Type);
Copy link
Member

Choose a reason for hiding this comment

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

@AnnaShaleva AttributeFee in memory pool can be 1, and during the block persistence can be changed to 2, this could underflow totalNetworkFee and produce a denial of service.

}
}
ECPoint[] validators = NEO.GetNextBlockValidators(engine.SnapshotCache, engine.ProtocolSettings.ValidatorsCount);
UInt160 primary = Contract.CreateSignatureRedeemScript(validators[engine.PersistingBlock.PrimaryIndex]).ToScriptHash();
Expand Down
82 changes: 76 additions & 6 deletions src/Neo/SmartContract/Native/PolicyContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ public sealed class PolicyContract : NativeContract
/// </summary>
public const uint DefaultAttributeFee = 0;

/// <summary>
/// The default fee for NotaryAssisted attribute.
/// </summary>
public const uint DefaultNotaryAssistedAttributeFee = 1000_0000;
AnnaShaleva marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>
/// The maximum execution fee factor that the committee can set.
/// </summary>
Expand Down Expand Up @@ -85,6 +90,10 @@ internal override ContractTask InitializeAsync(ApplicationEngine engine, Hardfor
engine.SnapshotCache.Add(_execFeeFactor, new StorageItem(DefaultExecFeeFactor));
engine.SnapshotCache.Add(_storagePrice, new StorageItem(DefaultStoragePrice));
}
if (hardfork == Hardfork.HF_Echidna)
{
engine.SnapshotCache.Add(CreateStorageKey(Prefix_AttributeFee).Add((byte)TransactionAttributeType.NotaryAssisted), new StorageItem(DefaultNotaryAssistedAttributeFee));
}
return ContractTask.CompletedTask;
}

Expand Down Expand Up @@ -122,15 +131,41 @@ public uint GetStoragePrice(DataCache snapshot)
}

/// <summary>
/// Gets the fee for attribute.
/// Gets the fee for attribute before Echidna hardfork.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="attributeType">Attribute type excluding <see cref="TransactionAttributeType.NotaryAssisted"/></param>
/// <returns>The fee for attribute.</returns>
[ContractMethod(Hardfork.HF_Echidna, CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates, Name = "getAttributeFee")]
public uint GetAttributeFeeV0(DataCache snapshot, byte attributeType)
{
return GetAttributeFee(snapshot, attributeType, false);
}

/// <summary>
/// Gets the fee for attribute after Echidna hardfork.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="attributeType">Attribute type</param>
/// <returns>The fee for attribute.</returns>
[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
[ContractMethod(true, Hardfork.HF_Echidna, CpuFee = 1 << 15, RequiredCallFlags = CallFlags.ReadStates)]
public uint GetAttributeFee(DataCache snapshot, byte attributeType)
{
if (!Enum.IsDefined(typeof(TransactionAttributeType), attributeType)) throw new InvalidOperationException();
return GetAttributeFee(snapshot, attributeType, true);
}

/// <summary>
/// Generic handler for GetAttributeFeeV0 and GetAttributeFeeV1 that
/// gets the fee for attribute.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="attributeType">Attribute type</param>
/// <param name="allowNotaryAssisted">Whether to support <see cref="TransactionAttributeType.NotaryAssisted"/> attribute type.</param>
/// <returns>The fee for attribute.</returns>
private uint GetAttributeFee(DataCache snapshot, byte attributeType, bool allowNotaryAssisted)
{
if (!Enum.IsDefined(typeof(TransactionAttributeType), attributeType) || (!allowNotaryAssisted && attributeType == (byte)(TransactionAttributeType.NotaryAssisted)))
throw new InvalidOperationException();
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
throw new InvalidOperationException();
throw new InvalidOperationException($"Invalid value {attributeType} of {nameof(attributeType)}");

StorageItem entry = snapshot.TryGet(CreateStorageKey(Prefix_AttributeFee).Add(attributeType));
if (entry == null) return DefaultAttributeFee;

Expand All @@ -149,10 +184,45 @@ public bool IsBlocked(DataCache snapshot, UInt160 account)
return snapshot.Contains(CreateStorageKey(Prefix_BlockedAccount).Add(account));
}

[ContractMethod(CpuFee = 1 << 15, RequiredCallFlags = CallFlags.States)]
private void SetAttributeFee(ApplicationEngine engine, byte attributeType, uint value)
/// <summary>
/// Sets the fee for attribute before Echidna hardfork.
/// </summary>
/// <param name="engine">The engine used to check committee witness and read data.</param>
/// <param name="attributeType">Attribute type excluding <see cref="TransactionAttributeType.NotaryAssisted"/></param>
/// <param name="value">Attribute fee value</param>
/// <returns>The fee for attribute.</returns>
[ContractMethod(Hardfork.HF_Echidna, CpuFee = 1 << 15, RequiredCallFlags = CallFlags.States, Name = "setAttributeFee")]
Copy link
Member

Choose a reason for hiding this comment

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

I think we don't need to change the manifest if only the logic changed, we can do it in the same method

private void SetAttributeFeeV0(ApplicationEngine engine, byte attributeType, uint value)
{
SetAttributeFee(engine, attributeType, value, false);
}

/// <summary>
/// Sets the fee for attribute after Echidna hardfork.
/// </summary>
/// <param name="engine">The engine used to check committee witness and read data.</param>
/// <param name="attributeType">Attribute type excluding <see cref="TransactionAttributeType.NotaryAssisted"/></param>
/// <param name="value">Attribute fee value</param>
/// <returns>The fee for attribute.</returns>
[ContractMethod(true, Hardfork.HF_Echidna, CpuFee = 1 << 15, RequiredCallFlags = CallFlags.States, Name = "setAttributeFee")]
private void SetAttributeFeeV1(ApplicationEngine engine, byte attributeType, uint value)
{
SetAttributeFee(engine, attributeType, value, true);
}

/// <summary>
/// Generic handler for SetAttributeFeeV0 and SetAttributeFeeV1 that
/// gets the fee for attribute.
/// </summary>
/// <param name="engine">The engine used to check committee witness and read data.</param>
/// <param name="attributeType">Attribute type</param>
/// <param name="value">Attribute fee value</param>
/// <param name="allowNotaryAssisted">Whether to support <see cref="TransactionAttributeType.NotaryAssisted"/> attribute type.</param>
/// <returns>The fee for attribute.</returns>
private void SetAttributeFee(ApplicationEngine engine, byte attributeType, uint value, bool allowNotaryAssisted)
{
if (!Enum.IsDefined(typeof(TransactionAttributeType), attributeType)) throw new InvalidOperationException();
if (!Enum.IsDefined(typeof(TransactionAttributeType), attributeType) || (!allowNotaryAssisted && attributeType == (byte)(TransactionAttributeType.NotaryAssisted)))
throw new InvalidOperationException();
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
throw new InvalidOperationException();
throw new InvalidOperationException($"Invalid value {attributeType} of {nameof(attributeType)}");

if (value > MaxAttributeFee) throw new ArgumentOutOfRangeException(nameof(value));
if (!CheckCommittee(engine)) throw new InvalidOperationException();

Expand Down
4 changes: 4 additions & 0 deletions src/Plugins/RpcClient/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ public static TransactionAttribute TransactionAttributeFromJson(JObject json)
{
Hash = UInt256.Parse(json["hash"].AsString())
},
TransactionAttributeType.NotaryAssisted => new NotaryAssisted()
{
NKeys = (byte)json["nkeys"].AsNumber()
},
_ => throw new FormatException(),
};
}
Expand Down
92 changes: 92 additions & 0 deletions tests/Neo.UnitTests/Network/P2P/Payloads/UT_NotaryAssisted.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright (C) 2015-2025 The Neo Project.
//
// UT_NotaryAssisted.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.

using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Extensions;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using System;

namespace Neo.UnitTests.Network.P2P.Payloads
{
[TestClass]
public class UT_NotaryAssisted
{
// Use the hard-coded Notary hash value from NeoGo to ensure hashes are compatible.
private static readonly UInt160 notaryHash = UInt160.Parse("0xc1e14f19c3e60d0b9244d06dd7ba9b113135ec3b");

[TestMethod]
public void Size_Get()
{
var attr = new NotaryAssisted() { NKeys = 4 };
attr.Size.Should().Be(1 + 1);
}

[TestMethod]
public void ToJson()
{
var attr = new NotaryAssisted() { NKeys = 4 };
var json = attr.ToJson().ToString();
Assert.AreEqual(@"{""type"":""NotaryAssisted"",""nkeys"":4}", json);
}

[TestMethod]
public void DeserializeAndSerialize()
{
var attr = new NotaryAssisted() { NKeys = 4 };

var clone = attr.ToArray().AsSerializable<NotaryAssisted>();
Assert.AreEqual(clone.Type, attr.Type);

// As transactionAttribute
byte[] buffer = attr.ToArray();
var reader = new MemoryReader(buffer);
clone = TransactionAttribute.DeserializeFrom(ref reader) as NotaryAssisted;
Assert.AreEqual(clone.Type, attr.Type);

// Wrong type
buffer[0] = 0xff;
Assert.ThrowsException<FormatException>(() =>
{
var reader = new MemoryReader(buffer);
TransactionAttribute.DeserializeFrom(ref reader);
});
}

[TestMethod]
public void Verify()
{
var attr = new NotaryAssisted() { NKeys = 4 };

// Temporary use Notary contract hash stub for valid transaction.
var txGood = new Transaction { Signers = new Signer[] { new Signer() { Account = notaryHash } } };
var txBad = new Transaction { Signers = new Signer[] { new Signer() { Account = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01") } } };
var snapshot = TestBlockchain.GetTestSnapshotCache();

Assert.IsTrue(attr.Verify(snapshot, txGood));
Assert.IsFalse(attr.Verify(snapshot, txBad));
}

[TestMethod]
public void CalculateNetworkFee()
{
var snapshot = TestBlockchain.GetTestSnapshotCache();
var attr = new NotaryAssisted() { NKeys = 4 };
var tx = new Transaction { Signers = new Signer[] { new Signer() { Account = notaryHash } } };

Assert.AreEqual((4 + 1) * 1000_0000, attr.CalculateNetworkFee(snapshot, tx));
}
}
}
2 changes: 1 addition & 1 deletion tests/Neo.UnitTests/Persistence/UT_MemoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public void NeoSystemStoreGetAndChange()

var entries = storeView.Seek([], SeekDirection.Backward).ToArray();
// Memory store has different seek behavior than the snapshot
Assert.AreEqual(entries.Length, 37);
Assert.AreEqual(entries.Length, 38);
}
}
}
Loading
Loading