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 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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
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-2024 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);
}
}
}
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 @@
/// 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/>.

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'

Check warning on line 46 in src/Neo/Network/P2P/Payloads/TransactionAttributeType.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

XML comment has badly formed XML -- 'Missing equals sign between attribute and attribute value.'
/// </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.Snapshot, (byte)notaryAssisted.Type);
AnnaShaleva marked this conversation as resolved.
Show resolved Hide resolved
}
}
ECPoint[] validators = NEO.GetNextBlockValidators(engine.Snapshot, engine.ProtocolSettings.ValidatorsCount);
UInt160 primary = Contract.CreateSignatureRedeemScript(validators[engine.PersistingBlock.PrimaryIndex]).ToScriptHash();
Expand Down
6 changes: 6 additions & 0 deletions src/Neo/SmartContract/Native/PolicyContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,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 @@ -73,6 +78,7 @@ internal override ContractTask InitializeAsync(ApplicationEngine engine, Hardfor
engine.Snapshot.Add(CreateStorageKey(Prefix_FeePerByte), new StorageItem(DefaultFeePerByte));
engine.Snapshot.Add(CreateStorageKey(Prefix_ExecFeeFactor), new StorageItem(DefaultExecFeeFactor));
engine.Snapshot.Add(CreateStorageKey(Prefix_StoragePrice), new StorageItem(DefaultStoragePrice));
engine.Snapshot.Add(CreateStorageKey(Prefix_AttributeFee).Add((byte)TransactionAttributeType.NotaryAssisted), new StorageItem(DefaultNotaryAssistedAttributeFee));
shargon marked this conversation as resolved.
Show resolved Hide resolved
}
return ContractTask.CompletedTask;
}
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 @@ -206,6 +206,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
91 changes: 91 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,91 @@
// Copyright (C) 2015-2024 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.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.GetTestSnapshot();

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

[TestMethod]
public void CalculateNetworkFee()
{
var snapshot = TestBlockchain.GetTestSnapshot();
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));
}
}
}
74 changes: 74 additions & 0 deletions tests/Neo.UnitTests/SmartContract/Native/UT_GasToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,35 @@
// modifications are permitted.

using FluentAssertions;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.SmartContract.Native;
using Neo.UnitTests.Extensions;
using Neo.UnitTests.Extensions;
using Neo.VM;
using Neo.Wallets;
using System;
using System;
using System;
using System.Linq;
using System.Linq;
using System.Numerics;
using System.Numerics;
using System.Numerics;
using System.Threading.Tasks;
using VMTypes = Neo.VM.Types;
// using VMArray = Neo.VM.Types.Array;

namespace Neo.UnitTests.SmartContract.Native
{
Expand Down Expand Up @@ -151,5 +169,61 @@ internal static StorageKey CreateStorageKey(byte prefix, byte[] key = null)
Key = buffer
};
}

[TestMethod]
public void Check_OnPersist_NotaryAssisted()
{
// Hardcode test values.
const uint defaultNotaryssestedFeePerKey = 1000_0000;
const byte NKeys1 = 4;
const byte NKeys2 = 6;

// Generate two transactions with NotaryAssisted attributes with hardcoded NKeys values.
var from = Contract.GetBFTAddress(TestProtocolSettings.Default.StandbyValidators);
var tx1 = TestUtils.GetTransaction(from);
tx1.Attributes = new TransactionAttribute[] { new NotaryAssisted() { NKeys = NKeys1 } };
var netFee1 = 1_0000_0000;
tx1.NetworkFee = netFee1;
var tx2 = TestUtils.GetTransaction(from);
tx2.Attributes = new TransactionAttribute[] { new NotaryAssisted() { NKeys = NKeys2 } };
var netFee2 = 2_0000_0000;
tx2.NetworkFee = netFee2;

// Calculate expected Notary nodes reward.
var expectedNotaryReward = (NKeys1 + 1) * defaultNotaryssestedFeePerKey + (NKeys2 + 1) * defaultNotaryssestedFeePerKey;

// Build block to check transaction fee distribution during Gas OnPersist.
var persistingBlock = new Block
{
Header = new Header
{
Index = (uint)TestProtocolSettings.Default.CommitteeMembersCount,
MerkleRoot = UInt256.Zero,
NextConsensus = UInt160.Zero,
PrevHash = UInt256.Zero,
Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() }
},
Transactions = new Transaction[] { tx1, tx2 }
};
var snapshot = _snapshot.CreateSnapshot();
var script = new ScriptBuilder();
script.EmitSysCall(ApplicationEngine.System_Contract_NativeOnPersist);
var engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot, persistingBlock, settings: TestBlockchain.TheNeoSystem.Settings);

// Check that block's Primary balance is 0.
ECPoint[] validators = NativeContract.NEO.GetNextBlockValidators(engine.Snapshot, engine.ProtocolSettings.ValidatorsCount);
var primary = Contract.CreateSignatureRedeemScript(validators[engine.PersistingBlock.PrimaryIndex]).ToScriptHash();
NativeContract.GAS.BalanceOf(engine.Snapshot, primary).Should().Be(0);

// Execute OnPersist script.
engine.LoadScript(script.ToArray());
Assert.IsTrue(engine.Execute() == VMState.HALT);

// Check that proper amount of GAS was minted to block's Primary and the rest
// will be minted to Notary nodes as a reward once Notary contract is implemented.
Assert.AreEqual(2 + 1, engine.Notifications.Count()); // burn tx1 and tx2 network fee + mint primary reward
Assert.AreEqual(netFee1 + netFee2 - expectedNotaryReward, engine.Notifications[2].State[2]);
NativeContract.GAS.BalanceOf(engine.Snapshot, primary).Should().Be(netFee1 + netFee2 - expectedNotaryReward);
}
}
}