This repository was archived by the owner on Dec 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 224
node: Cli: Adding Script System for neo-cli #901
Open
Jim8y
wants to merge
6
commits into
neo-project:master
Choose a base branch
from
Jim8y:cli-script
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
01b43da
script
Jim8y 625b55d
add script system
Jim8y 56ef8ba
remove the template from the compile
Jim8y 2ee16b8
Merge branch 'master' into cli-script
Jim8y 32de581
Merge branch 'master' into cli-script
Jim8y c42531a
Merge branch 'master' into cli-script
superboyiii File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
// Copyright (C) 2016-2023 The Neo Project. | ||
// | ||
// The neo-cli is free software distributed under the MIT software | ||
// license, see the accompanying file LICENSE in the main directory of | ||
// the project 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 Microsoft.CodeAnalysis.CSharp.Scripting; | ||
using Microsoft.CodeAnalysis.Scripting; | ||
using Neo.ConsoleService; | ||
using System; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Neo.SmartContract.Native; | ||
|
||
namespace Neo.CLI | ||
{ | ||
partial class MainService | ||
{ | ||
/// <summary> | ||
/// Create a new script file from the template | ||
/// </summary> | ||
/// <param name="path">Path of the new script file</param> | ||
/// <example>new script script.cs</example> | ||
[ConsoleCommand("script new", Category = "Command Script")] | ||
private void OnCreatingNewScript(String path = null) | ||
{ | ||
if (string.IsNullOrEmpty(path)) | ||
{ | ||
path = "script.cs"; | ||
} | ||
|
||
if (!File.Exists(path)) | ||
{ | ||
ConsoleHelper.Info($"File {path} does not exist. Attempting to generate from template..."); | ||
|
||
if (!File.Exists("template.cs")) | ||
{ | ||
ConsoleHelper.Error("Template file 'template.cs' does not exist. Unable to generate script."); | ||
return; | ||
} | ||
|
||
File.Copy("template.cs", path); | ||
ConsoleHelper.Info($"File {path} generated from template."); | ||
} | ||
else | ||
{ | ||
ConsoleHelper.Info($"File {path} already exists. No action taken."); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Execute the script file | ||
/// </summary> | ||
/// <param name="path">path of the script file, script.cs if not given</param> | ||
/// <param name="watch"></param> | ||
/// <example>run script script.cs true</example> | ||
[ConsoleCommand("script run", Category = "Command Script")] | ||
private async Task OnExecutingScript(String path = null, bool watch = false) | ||
{ | ||
if (string.IsNullOrEmpty(path)) | ||
{ | ||
path = "script.cs"; | ||
} | ||
|
||
if (!File.Exists(path)) | ||
{ | ||
ConsoleHelper.Error($"File {path} does not exist. Please create it using the 'new script' command."); | ||
return; | ||
} | ||
|
||
ConsoleHelper.Info("Executing script..."); | ||
ConsoleHelper.Info("Path: " + path); | ||
|
||
// Execute the script once initially | ||
await ExecuteScript(path); | ||
|
||
if (watch) | ||
{ | ||
// Use FileSystemWatcher to watch the file for changes | ||
using var watcher = new FileSystemWatcher(); | ||
watcher.Path = Path.GetDirectoryName(path)!; | ||
watcher.Filter = Path.GetFileName(path); | ||
watcher.NotifyFilter = NotifyFilters.LastWrite; | ||
|
||
watcher.Changed += async (source, e) => | ||
{ | ||
ConsoleHelper.Info($"File {e.FullPath} changed. Re-executing script..."); | ||
await ExecuteScript(path); | ||
}; | ||
|
||
watcher.EnableRaisingEvents = true; | ||
|
||
ConsoleHelper.Info($"Watching for changes to {path}..."); | ||
ConsoleHelper.Info("Press any key to stop watching..."); | ||
Console.ReadKey(); | ||
} | ||
} | ||
|
||
private async Task ExecuteScript(string path) | ||
{ | ||
await Task.Run(async () => | ||
{ | ||
try | ||
{ | ||
await CSharpScript.EvaluateAsync( | ||
await File.ReadAllTextAsync(path), | ||
ScriptOptions.Default.WithImports("System", "System.Threading", "System.Linq").WithReferences(typeof(NeoSystem).Assembly, typeof(ScriptHelper.ScriptHelper).Assembly), | ||
globals: this | ||
); | ||
ConsoleHelper.Info("Result: " + NativeContract.Contracts.ToList().Count); | ||
} | ||
catch (Exception e) | ||
{ | ||
Console.Error.WriteLine($"{e}"); | ||
} | ||
}); | ||
} | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Copyright (C) 2016-2023 The Neo Project. | ||
// | ||
// The neo-cli is free software distributed under the MIT software | ||
// license, see the accompanying file LICENSE in the main directory of | ||
// the project 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 System.Collections.Generic; | ||
using System.Threading.Tasks; | ||
using Akka.Actor; | ||
using Neo.Ledger; | ||
using Neo.Network.P2P.Payloads; | ||
using Neo.Persistence; | ||
|
||
namespace Neo.ScriptHelper | ||
{ | ||
public class ScriptHelper | ||
{ | ||
private readonly NeoSystem _neoSystem; | ||
|
||
public ScriptHelper(NeoSystem neoSystem) | ||
{ | ||
_neoSystem = neoSystem; | ||
Blockchain.Committing += OnCommitting; | ||
Blockchain.Committed += OnCommitted; | ||
} | ||
|
||
private Dictionary<UInt256, TaskCompletionSource<Blockchain.ApplicationExecuted>> transactionCompletionSources | ||
= new(); | ||
|
||
private TaskCompletionSource<Block> _blockStream = new(); | ||
|
||
public async Task<Blockchain.ApplicationExecuted> SendRawTransactionAsync(Transaction tx) | ||
{ | ||
var tcs = new TaskCompletionSource<Blockchain.ApplicationExecuted>(); | ||
|
||
// Store the TaskCompletionSource for this transaction | ||
transactionCompletionSources[tx.Hash] = tcs; | ||
|
||
// Broadcast the transaction | ||
_neoSystem.Blockchain.Tell(tx, ActorRefs.NoSender); | ||
|
||
return await tcs.Task; | ||
} | ||
|
||
private void OnCommitting(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList<Blockchain.ApplicationExecuted> applicationExecutedList) | ||
{ | ||
foreach (var tx in applicationExecutedList) | ||
{ | ||
if (!transactionCompletionSources.TryGetValue(tx.Transaction.Hash, out var tcs)) continue; | ||
tcs.SetResult(tx); | ||
|
||
transactionCompletionSources.Remove(tx.Transaction.Hash); | ||
} | ||
} | ||
|
||
private void OnCommitted(NeoSystem system, Block block) | ||
{ | ||
_blockStream.SetResult(block); | ||
} | ||
|
||
public async Task<Block> OnNewBlock() | ||
{ | ||
var tcs = new TaskCompletionSource<Block>(); | ||
// Store the TaskCompletionSource for this transaction | ||
_blockStream = tcs; | ||
return await tcs.Task; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// Copyright (C) 2016-2023 The Neo Project. | ||
// | ||
// The neo-cli is free software distributed under the MIT software | ||
// license, see the accompanying file LICENSE in the main directory of | ||
// the project 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 System; | ||
using System.Linq; | ||
using Neo; | ||
using Neo.SmartContract; | ||
using Neo.SmartContract.Native; | ||
using Neo.Network.P2P.Payloads; | ||
using Neo.Wallets; | ||
using Neo.VM; | ||
using Neo.ScriptHelper; | ||
|
||
#if DEBUG | ||
NeoSystem NeoSystem = new(null); | ||
#endif | ||
|
||
// Create an instance of ScriptHelper | ||
ScriptHelper helper = new ScriptHelper(NeoSystem); | ||
|
||
// loading key pair | ||
var keyPair = new KeyPair(Wallet.GetPrivateKeyFromWIF("xxxxxxxxxxxxxxxxxxxxxxxx-your private key")); | ||
var scriptHash = Contract.CreateSignatureContract(keyPair.PublicKey).ScriptHash; | ||
Console.WriteLine($"ME: {scriptHash} {scriptHash.ToAddress(NeoSystem.Settings.AddressVersion)}"); | ||
|
||
// get snapshot | ||
var snapshot = NeoSystem.GetSnapshot(); | ||
// get latest block index | ||
var blockIndex = NativeContract.Ledger.CurrentIndex(snapshot); | ||
// get latest block | ||
var block = NativeContract.Ledger.GetBlock(snapshot, blockIndex); | ||
|
||
// constructing transaction | ||
var msg = @"XXX"; | ||
var sb = new ScriptBuilder(); | ||
sb.EmitPush(msg); | ||
var transaction = new Transaction | ||
{ | ||
Version = 0, | ||
Nonce = (uint)new Random().NextInt64(), | ||
SystemFee = 1000000, | ||
NetworkFee = 0x3e500, | ||
Attributes = new TransactionAttribute[], | ||
Script = sb.ToArray(), | ||
Signers = new Signer[] { new Signer { Account = scriptHash, Scopes = WitnessScope.CalledByEntry } }, | ||
ValidUntilBlock = blockIndex + 1, | ||
}; | ||
|
||
// sign the transaction | ||
var signature = transaction.Sign(keyPair, NeoSystem.Settings.Network); | ||
var invocationScript = new byte[] { ((byte)OpCode.PUSHDATA1), 64 }.Concat(signature).ToArray(); | ||
var verificationScript = Contract.CreateSignatureContract(keyPair.PublicKey).Script; | ||
transaction.Witnesses = new Witness[] { new Witness { InvocationScript = invocationScript, VerificationScript = verificationScript } }; | ||
Console.WriteLine($"HASH: {transaction.Hash}"); | ||
Console.WriteLine($"{transaction.Verify(NeoSystem.Settings, snapshot, new(), new Transaction[] { })}"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe should be |
||
|
||
|
||
var txRes = await helper.SendRawTransactionAsync(transaction); | ||
|
||
|
||
|
||
// // get validators | ||
// var validators = NativeContract.NEO.GetNextBlockValidators(snapshot, NeoSystem.Settings.ValidatorsCount); | ||
// // get next primary | ||
// UInt160 primary = Contract.CreateSignatureRedeemScript(validators[(block.PrimaryIndex + 1) % NeoSystem.Settings.ValidatorsCount]).ToScriptHash(); | ||
// Console.WriteLine($"NEXT SPEAKER: {primary.ToAddress(NeoSystem.Settings.AddressVersion)}"); | ||
// | ||
// Console.WriteLine($"{NativeContract.NEO.BalanceOf(NeoSystem.GetSnapshot(), UInt160.Zero)}"); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Plus
NeoSystem.Settings.MaxValidUntilBlockIncrement
?