private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal) { bb.PrevHash = val256; merkRootVal = UInt256.Parse("0xd841af3d6bd7adb4bca24306725f9aec363edb10de3cafc5f8cca948d7b0290f"); bb.MerkleRoot = merkRootVal; timestampVal = new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc).ToTimestampMS(); // GMT: Sunday, June 1, 1980 12:00:01.001 AM bb.Timestamp = timestampVal; indexVal = 0; bb.Index = indexVal; val160 = UInt160.Zero; bb.NextConsensus = val160; scriptVal = new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSHT } }; bb.Witness = scriptVal; }
private void assertStandardHeaderTestVals(UInt256 val256, UInt256 merkRoot, UInt160 val160, uint timestampVal, uint indexVal, Witness scriptVal) { uut.PrevHash.Should().Be(val256); uut.MerkleRoot.Should().Be(merkRoot); uut.Timestamp.Should().Be(timestampVal); uut.Index.Should().Be(indexVal); uut.NextConsensus.Should().Be(val160); uut.Witness.InvocationScript.Length.Should().Be(0); uut.Witness.Size.Should().Be(scriptVal.Size); uut.Witness.VerificationScript[0].Should().Be(scriptVal.VerificationScript[0]); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); // those you need to set up------------------------------------------------------------ rpcClient = new RpcClient("http://localhost:20002"); // your node url, such as "http://47.89.240.111:12332" nep2Key = "6PYLjXkQzADs7r36XQjByJXoggm3beRh6UzxuN59NZiBxFBnm1HPvv3ytM"; // you can find this in your wallet, the "key" field string password = "******"; // your password UInt160 from = "AQzRMe3zyGS8W177xLJfewRRQZY2kddMun".ToScriptHash(); // your account address, such as "APPmjituYcgfNxjuQDy9vP73R2PmhFsYJR" UInt160 scriptHash = UInt160.Parse("0x6b4f6926c28523519c758ec2015a60ddfe8b37dc"); // your contract script hash, such as "0x5be5fc0641e44b0003262b3fda775ea60133cb05" //byte[] param = new byte[] { }; // your contract parameter BigInteger param = 2; //------------------------------------------------------------------------------------------- ScriptBuilder sb = new ScriptBuilder().EmitAppCall(scriptHash, "getProxyHash", new ContractParameter[] { new ContractParameter() { Type = ContractParameterType.Integer, Value = param } }); var script = sb.ToArray(); InvocationTransaction itx = new InvocationTransaction(); itx.Inputs = new CoinReference[] { }; itx.Outputs = new TransactionOutput[] { }; itx.Attributes = new TransactionAttribute[] { }; itx.Witnesses = new Witness[] { }; itx.Version = 1; itx.Script = script; itx.Gas = GetGasConsumed(script); Fixed8 fee = itx.Gas; if (itx.Size > 1024) { fee += Fixed8.FromDecimal(0.001m); fee += Fixed8.FromDecimal(itx.Size * 0.00001m); } var(inputs, sum) = GetTransactionInputs(from, Blockchain.UtilityToken.Hash, fee); if (sum > fee) { itx.Outputs = itx.Outputs.Concat(new[] { new TransactionOutput() { AssetId = Blockchain.UtilityToken.Hash, Value = sum - fee, ScriptHash = from } }).ToArray(); } itx.Inputs = itx.Inputs.Concat(inputs).ToArray(); // sign the itx Random random = new Random(); var nonce = new byte[32]; random.NextBytes(nonce); TransactionAttribute[] attributes = new TransactionAttribute[] { new TransactionAttribute() { Usage = TransactionAttributeUsage.Script, Data = from.ToArray() }, new TransactionAttribute() { Usage = TransactionAttributeUsage.Remark1, Data = nonce } // if a transaction has no inputs and outputs, need to add nonce for duplication }; itx.Attributes = itx.Attributes.Concat(attributes).ToArray(); KeyPair keyPair = WalletHelper.KeyPairFromNep2(nep2Key, password); Witness witness = WalletHelper.CreateTransactionWitness(itx, keyPair); itx.Witnesses = itx.Witnesses.Concat(new[] { witness }).ToArray(); var raw = itx.ToArray(); var txid = rpcClient.SendRawTransaction(raw); Console.WriteLine(txid.ToString()); }
public static void SetupHeaderWithValues(Header header, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal) { setupBlockBaseWithValues(header, val256, out merkRootVal, out val160, out timestampVal, out indexVal, out scriptVal); }
private double GetScoreForRelationalInformation(Witness witness) { // assert (x != null) if(witness.WarningKind == WarningKind.Assert && ContainsWarningContext(witness, WarningContext.ContextType.IsVarNotEqNullCheck)) { return ScoreRelationalIsAssertAndVarNullCheck; } // Requires(a.Property != null) if(witness.WarningKind == WarningKind.MissingPrecondition && ContainsWarningContext(witness, WarningContext.ContextType.IsPureMethodCallNotEqNullCheck)) { return ScoreRelationalIsMissingPreconditionAndPureMethodNullCheck; } return 1.0; }
public void TestSetup() { uut = new Witness(); TestBlockchain.InitializeMockNeoSystem(); }
public static void Refund() { var inputs = new List <CoinReference> { new CoinReference() { PrevHash = new UInt256("0x44d5a5ef32c8ec780de59ca59cb799efd1bf3051d9a2c94a2b1d13af34abe7ca".Remove(0, 2).HexToBytes().Reverse().ToArray()), PrevIndex = 0 } }.ToArray(); var outputs = new List <TransactionOutput> { new TransactionOutput() { AssetId = Blockchain.UtilityToken.Hash, //Asset Id, this is GAS ScriptHash = ScriptHash, //CGAS 地址 Value = new Fixed8((long)(9.99 * (long)Math.Pow(10, 8))) } }.ToArray(); Transaction tx = null; var applicationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitAppCall(ScriptHash, "refund", User); sb.Emit(OpCode.THROWIFNOT); applicationScript = sb.ToArray(); } tx = new InvocationTransaction { Version = 0, Script = applicationScript, Outputs = outputs, Inputs = inputs, Attributes = new TransactionAttribute[] { new TransactionAttribute { Usage = TransactionAttributeUsage.Script, Data = User.ToArray()//附加人的 Script Hash } } }; //Open wallet var wallet = new Neo.Wallets.NEP6.NEP6Wallet(new WalletIndexer("Index_0001E240"), "1.json"); try { wallet.Unlock("11111111"); } catch (Exception) { Console.WriteLine("password error"); } //Sign in wallet 生成附加人的签名 var context = new ContractParametersContext(tx); var additionalSignature = new byte[0]; foreach (UInt160 hash in context.ScriptHashes) { if (hash == User) { WalletAccount account = wallet.GetAccount(hash); if (account?.HasKey != true) { continue; } KeyPair key = account.GetKey(); additionalSignature = context.Verifiable.Sign(key); } } var additionalVerificationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(additionalSignature); additionalVerificationScript = sb.ToArray(); } var verificationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(2); sb.EmitPush("1"); verificationScript = sb.ToArray(); } var witness = new Witness { InvocationScript = verificationScript, VerificationScript = Blockchain.Singleton.Store.GetContracts().TryGet(ScriptHash).Script }; var additionalWitness = new Witness { InvocationScript = additionalVerificationScript, VerificationScript = UserScript }; var witnesses = new Witness[2] { witness, additionalWitness }; tx.Witnesses = witnesses.ToList().OrderBy(p => p.ScriptHash).ToArray(); Verify(tx); }
public bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args) { Contract.Requires(witness != null); Contract.Requires(format != null); return false; }
public static void Refund() { var inputs = new List <CoinReference> { new CoinReference() { PrevHash = new UInt256("0xdb4c4f1a17b365a68497ef0e118db89b827db24f67ee71d317d38c68c84424ef".Remove(0, 2).HexToBytes().Reverse().ToArray()), PrevIndex = 0 //1 } }.ToArray(); var outputs = new List <TransactionOutput> { new TransactionOutput() { AssetId = Blockchain.UtilityToken.Hash, //Asset Id, this is GAS ScriptHash = SgasAddress, //SGAS 地址 Value = new Fixed8((long)(1 * (long)Math.Pow(10, 8))) //Value } }.ToArray(); Transaction tx = null; var applicationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitAppCall(ScriptHash, "refund", User); sb.Emit(OpCode.THROWIFNOT); applicationScript = sb.ToArray(); } tx = new InvocationTransaction { Version = 0, Script = applicationScript, Outputs = outputs, Inputs = inputs, Attributes = new TransactionAttribute[] { new TransactionAttribute { Usage = TransactionAttributeUsage.Script, Data = User.ToArray()//附加人的 Script Hash } } }; if (tx == null) { Console.WriteLine("Create Transaction Failed"); Console.ReadLine(); return; } //Open wallet var wallet = new Neo.Implementations.Wallets.NEP6.NEP6Wallet("0.json"); try { wallet.Unlock("1"); } catch (Exception) { Console.WriteLine("password error"); } //Sign in wallet 生成附加人的签名 var context = new ContractParametersContext(tx); var additionalSignature = new byte[0]; foreach (UInt160 hash in context.ScriptHashes) { if (hash == User) { WalletAccount account = wallet.GetAccount(hash); if (account?.HasKey != true) { continue; } KeyPair key = account.GetKey(); additionalSignature = context.Verifiable.Sign(key); } } var additionalVerificationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(additionalSignature); additionalVerificationScript = sb.ToArray(); } var verificationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(2); sb.EmitPush("1"); verificationScript = sb.ToArray(); } var witness = new Witness { InvocationScript = verificationScript, VerificationScript = Blockchain.Default.GetContract(ScriptHash).Script }; var additionalWitness = new Witness { InvocationScript = additionalVerificationScript, VerificationScript = UserScript }; var witnesses = new Witness[2] { witness, additionalWitness }; tx.Scripts = witnesses.ToList().OrderBy(p => p.ScriptHash).ToArray(); try { tx = Transaction.DeserializeFrom(tx.ToArray()); } catch (Exception) { Console.WriteLine("Invalid Transaction Format"); } if (tx.Verify(new List <Transaction> { tx })) { Console.WriteLine("Verify Transaction: True"); Console.WriteLine("Raw Transaction:"); Console.WriteLine(tx.ToArray().ToHexString()); //Console.WriteLine(tx.ToJson()); //Then Call neo-cli API:sendrawtransaction in postman. } else { Console.WriteLine("Verify Transaction: False"); } }
public static void Verify() { var inputs = new List <CoinReference> { new CoinReference() { PrevHash = new UInt256("0xdb4c4f1a17b365a68497ef0e118db89b827db24f67ee71d317d38c68c84424ef".Remove(0, 2).HexToBytes().Reverse().ToArray()), PrevIndex = 0 //1 } }.ToArray(); var outputs = new List <TransactionOutput> { new TransactionOutput() { AssetId = Blockchain.UtilityToken.Hash, //Asset Id, this is GAS ScriptHash = SgasAddress, //SGAS 地址 Value = new Fixed8((long)(1 * (long)Math.Pow(10, 8))) //Value } }.ToArray(); Transaction tx = null; var verificationScript = new byte[0]; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(2); sb.EmitPush("1"); verificationScript = sb.ToArray(); } var witness = new Witness { InvocationScript = verificationScript, //未部署的合约不能执行 Storage.Get() 方法,所以要将合约部署,而不是调用本地的 AVM 文件 //VerificationScript = File.ReadAllBytes("C:\\Users\\chenz\\Documents\\1Code\\chenzhitong\\NeoContract5\\NeoContract\\bin\\Debug\\SGAS.avm") VerificationScript = Blockchain.Default.GetContract(ScriptHash).Script }; tx = new InvocationTransaction { Version = 0, Script = new byte[0], Outputs = outputs, Inputs = inputs, Attributes = new TransactionAttribute[0], Scripts = new Witness[] { witness } }; if (tx == null) { Console.WriteLine("Create Transaction Failed"); Console.ReadLine(); return; } try { tx = Transaction.DeserializeFrom(tx.ToArray()); } catch (Exception) { Console.WriteLine("Invalid Transaction Format"); } if (tx.Verify(new List <Transaction> { tx })) { Console.WriteLine("Verify Transaction: True"); Console.WriteLine("Raw Transaction:"); Console.WriteLine(tx.ToArray().ToHexString()); //Console.WriteLine(tx.ToJson()); //Then Call neo-cli API:sendrawtransaction in postman. } else { Console.WriteLine("Verify Transaction: False"); } }
bool IOutputResults.IsMasked(Witness witness) { throw new NotImplementedException(); }
bool IOutputResults.EmitOutcome(Witness witness, string format, params object[] args) { if (this.ShowOnlyAnswersToAskClousot) { return(false); } string tag; switch (witness.Outcome) { case ProofOutcome.Top: tag = "warning"; break; case ProofOutcome.False: tag = "error"; break; default: tag = ""; break; } ICodeAction action = null; // No action for a warning/error. Suggestions have actions. var msg = String.Format("{0}: {1}", tag, String.Format(format, args)); var startIndex = 0; var length = 0; var pc = witness.PC.PrimaryMethodLocation(); if (pc.HasRealSourceContext) { startIndex = pc.Block.SourceStartIndex(pc); length = pc.Block.SourceLength(pc); var startLine = pc.Block.SourceStartLine(pc); var startColumn = pc.Block.SourceStartColumn(pc); this.results.Add(new ClousotOutput(witness.Outcome, msg, new TextSpan(startIndex, length), new Tuple <int, int>(startLine, startColumn), action, ClousotOutput.ExtraInfo.None)); return(true); } if (pc.InsideEnsuresInMethod) // postcondition failures don't have good locations { MethodReferenceAdaptor meth; var ok = pc.TryGetContainingMethod(out meth); if (ok && IteratorHelper.EnumerableIsNotEmpty(meth.reference.Locations)) { var l = IteratorHelper.First(meth.reference.Locations) as ISourceLocation; if (l != null) { startIndex = l.StartIndex; length = l.Length; var s = new TextSpan(startIndex, length); BaseMethodDeclarationSyntax m; if (this.span2Method.TryGetValue(s, out m)) { List <TextSpan> returnSpans = null; if (m is MethodDeclarationSyntax) // otherwise it is a constructor { returnSpans = ReturnStatementFinder.GetReturnStatementSpans(m as MethodDeclarationSyntax); } if (returnSpans == null || returnSpans.Count == 0) { if (m.Body == null) { this.results.Add(new ClousotOutput(witness.Outcome, msg, m.GetLastToken().Span, null, action, ClousotOutput.ExtraInfo.None)); return(true); } else { // just use method's closing curly this.results.Add(new ClousotOutput(witness.Outcome, msg, m.Body.CloseBraceToken.Span, null, action, ClousotOutput.ExtraInfo.None)); return(true); } } else { foreach (var returnSpan in returnSpans) { this.results.Add(new ClousotOutput(witness.Outcome, msg, returnSpan, null, action, ClousotOutput.ExtraInfo.None)); } return(true); } } } } } return(false); }
private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out uint timestampVal, out uint indexVal, out Witness scriptVal) { bb.PrevHash = val256; merkRootVal = new UInt256(new byte[] { 242, 128, 130, 9, 63, 13, 149, 96, 141, 161, 52, 196, 148, 141, 241, 126, 172, 102, 108, 194, 91, 50, 128, 91, 64, 116, 127, 40, 58, 171, 158, 197 }); bb.MerkleRoot = merkRootVal; timestampVal = new DateTime(1968, 06, 01, 0, 0, 0, DateTimeKind.Utc).ToTimestamp(); bb.Timestamp = timestampVal; indexVal = 0; bb.Index = indexVal; val160 = UInt160.Zero; bb.NextConsensus = val160; scriptVal = new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSHT } }; bb.Witness = scriptVal; }
private void assertStandardBlockTestVals(UInt256 val256, UInt256 merkRoot, UInt160 val160, uint timestampVal, uint indexVal, ulong consensusDataVal, Witness scriptVal, Transaction[] transactionsVal, bool testTransactions = true) { uut.PrevHash.Should().Be(val256); uut.MerkleRoot.Should().Be(merkRoot); uut.Timestamp.Should().Be(timestampVal); uut.Index.Should().Be(indexVal); uut.ConsensusData.Should().Be(consensusDataVal); uut.NextConsensus.Should().Be(val160); uut.Script.InvocationScript.Length.Should().Be(0); uut.Script.Size.Should().Be(scriptVal.Size); uut.Script.VerificationScript[0].Should().Be(scriptVal.VerificationScript[0]); if (testTransactions) { uut.Transactions.Length.Should().Be(1); uut.Transactions[0].Should().Be(transactionsVal[0]); } }
internal static bool VerifyWitness(this IVerifiable verifiable, StoreView snapshot, UInt160 hash, Witness witness, long gas, out long fee) { fee = 0; using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.Clone(), gas)) { CallFlags callFlags = !witness.VerificationScript.IsStandardContract() ? CallFlags.ReadStates : CallFlags.None; byte[] verification = witness.VerificationScript; if (verification.Length == 0) { ContractState cs = NativeContract.Management.GetContract(snapshot, hash); if (cs is null) { return(false); } if (engine.LoadContract(cs, "verify", callFlags, true) is null) { return(false); } } else { if (NativeContract.IsNative(hash)) { return(false); } if (hash != witness.ScriptHash) { return(false); } engine.LoadScript(verification, callFlags, hash, 0); } engine.LoadScript(witness.InvocationScript, CallFlags.None); if (engine.Execute() == VMState.FAULT) { return(false); } if (engine.ResultStack.Count != 1 || !engine.ResultStack.Peek().GetBoolean()) { return(false); } fee = engine.GasConsumed; } return(true); }
public static void SetupBlockWithValues(Block block, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal, out Transaction[] transactionsVal, int numberOfTransactions) { Header header = new Header(); SetupHeaderWithValues(header, val256, out merkRootVal, out val160, out timestampVal, out indexVal, out scriptVal); transactionsVal = new Transaction[numberOfTransactions]; if (numberOfTransactions > 0) { for (int i = 0; i < numberOfTransactions; i++) { transactionsVal[i] = GetTransaction(UInt160.Zero); } } block.Header = header; block.Transactions = transactionsVal; header.MerkleRoot = merkRootVal = MerkleTree.ComputeRoot(block.Transactions.Select(p => p.Hash).ToArray()); }
public ActionResult Loan(FormCollection fc) { bool status = false; decimal loanamt = Convert.ToDecimal(fc["amt"]); int terms = Convert.ToInt32(fc["mtp"]); decimal totalwinterest = Convert.ToDecimal(fc["totalwinterest"]); int mid = Convert.ToInt32(Session["MemberId"]); string w1 = Convert.ToString(fc["witness1"]); string w2 = Convert.ToString(fc["witness2"]); string w3 = Convert.ToString(fc["witness3"]); int no = Convert.ToInt32(fc["no"]); List <Loan> listloan = new List <Loan>(); listloan = LoanControllerSql.GetAll(); int cid = listloan.Count + 1; string lid = "L" + cid.ToString(); DateTime d = DateTime.Now; Loan loan = new Loan { LoanId = lid, MemberId = mid, Status = "Pending", CreatedDate = d, ApprovalDate = d, LoanAmt = loanamt, Terms = terms, InterestRate = 1, TotalPaymentwInterest = totalwinterest, ApprovedBy = "none" }; status = LoanControllerSql.Insert(loan); if (status == true) { Witness w = new Witness { LoanId = lid, WitnessName = w1, }; status = WitnessControllerSql.Insert(w); Witness wm1 = new Witness { LoanId = lid, WitnessName = w2, }; status = WitnessControllerSql.Insert(wm1); Witness wm2 = new Witness { LoanId = lid, WitnessName = w3, }; status = WitnessControllerSql.Insert(wm2); Response.Write("<script>alert('Success');</script>"); for (int i = 0; i <= no - 1; i++) { string name = Convert.ToString(fc["co" + i]); string contact = Convert.ToString(fc["cno" + i]); string MID = Convert.ToString(fc["CMID" + i]); if (MID == "") { MID = "0"; } List <Member> m = new List <Member>(); m = MemberControllerSql.Get(MID); if (m.Count > 0) { Comaker co = new Comaker { LoanId = lid, Name = name, ContactNo = contact, MemberId = MID }; status = ComakerControllerSql.Insert(co); } else { Response.Write("<script type='text/javascript'>alert(Member Id: " + MID + "' doesn't exist');</script>"); return(View()); } } if (status == true) { Session["Success"] = "1"; return(RedirectToAction("Home", "Member")); } } return(View()); }
public Tuple<double, List<string>> GetScore(Witness witness) { Contract.Requires(witness != null); Contract.Ensures(0.0 <= Contract.Result<Tuple<double, List<string>>>().Item1); Contract.Ensures(Contract.Result<Tuple<double, List<string>>>().Item1 <= 2.0); Contract.Ensures(Contract.Result<Tuple<double, List<string>>>().Item2 != null); List<string> why; var ScoreForOutcome = this.GetScoreForOutcome(witness.Outcome); var ScoreForWarning = this.GetScoreForWarningType(witness.Warning); var ScoreForContext = this.GetScoreForWarningContexts(witness.Context, out why); var ScoreForPC = this.GetScoreForPC(witness.PC); var ScoreForRelationalInformation = this.GetScoreForRelationalInformation(witness); var result = ScoreForOutcome * ScoreForWarning * ScoreForContext * ScoreForPC * ScoreForRelationalInformation; Contract.Assume(!double.IsNaN(result)); var score = NormalizeScore(result); return new Tuple<double, List<string>>(score, why); }
private void CalcSpotted(Witness witness) { float spottedMultiplier = 1f; if (Config.Options.ArrestWarrants.Enabled) { spottedMultiplier = Config.Options.ArrestWarrants.SpotSpeed / 100f; } // Ped Spotted if (ArrestWarrants.IsWarrantSearchActive) { spottedMultiplier = ArrestWarrants.PedMatch * spottedMultiplier; } if (witness.Recognition >= 0 && witness.Recognition <= 25) { witness.Spotted += -1 * spottedMultiplier; } else if (witness.Recognition > 25 && witness.Recognition < 50) { witness.Spotted += -0.25 * spottedMultiplier; } else if (witness.Recognition >= 50 && witness.Recognition < 75) { if (witness.Spotted < 20) { witness.Spotted += 0.25 * spottedMultiplier; } } else if (witness.Recognition >= 75 && witness.Recognition < 100) { witness.Spotted += 0.5 * spottedMultiplier; } else if (witness.Recognition >= 100) { witness.Spotted += 5 * spottedMultiplier; } if (witness.Spotted > 100) { witness.Spotted = 100; } if (witness.Spotted < 0) { witness.Spotted = 0; } //// RESET spottedMultiplier = 1f; if (Config.Options.ArrestWarrants.Enabled) { spottedMultiplier = Config.Options.ArrestWarrants.SpotSpeed / 100f; } // Vehicle Spotted if (ArrestWarrants.IsWarrantSearchActive) { spottedMultiplier = ArrestWarrants.VehicleMatch * spottedMultiplier; } if (witness.VehicleRecognition >= 0 && witness.VehicleRecognition <= 25) { witness.VehicleSpotted += -1 * spottedMultiplier; } else if (witness.VehicleRecognition > 25 && witness.VehicleRecognition < 50) { witness.VehicleSpotted += -0.25 * spottedMultiplier; } else if (witness.VehicleRecognition >= 50 && witness.VehicleRecognition < 75) { if (witness.VehicleSpotted < 20) { witness.VehicleSpotted += 0.25 * spottedMultiplier; } } else if (witness.VehicleRecognition >= 75 && witness.VehicleRecognition < 100) { witness.VehicleSpotted += 0.5 * spottedMultiplier; } else if (witness.VehicleRecognition >= 100) { witness.VehicleSpotted += 5 * spottedMultiplier; } if (witness.VehicleSpotted > 100) { witness.VehicleSpotted = 100; } if (witness.VehicleSpotted < 0) { witness.VehicleSpotted = 0; } }
static private bool ContainsWarningContext(Witness witness, WarningContext.ContextType what) { return witness.Context.Any(wc => wc.Type == what); }
private void OnTick(object sender, EventArgs e) { if (!ArrestWarrants.CopSearch && !BetterChases.CopSearch) { Citizens.Clear(); Cops.Clear(); return; } Ped Character = Game.Player.Character; Vehicle CurrentVehicle = Game.Player.Character.CurrentVehicle; int WantedLevel = Game.Player.WantedLevel; vehicleSize = 0; MaxWitnessDistance = 60f; if (Helpers.IsValid(CurrentVehicle)) { // Calculate vehicle size //Vector3 dimensions = CurrentVehicle.Model.Dimensions; vehicleSize = 500; // dimensions.X + dimensions.Y + dimensions.Z; // Calculate witness distance MaxWitnessDistance = Math.Min(60f, vehicleSize * MaxWitnessDistance / 4); } //System.Diagnostics.Stopwatch Stopwatch = System.Diagnostics.Stopwatch.StartNew(); //Stopwatch.Start(); // Citizens for (int i = Citizens.Count - 1; i >= 0; i--) { Witness citizen = Citizens[i]; if (!citizen.Ped.IsAlive) { //citizen.Ped.CurrentBlip.Remove(); Citizens.Remove(citizen); continue; } RaycastResult ray = new RaycastResult(); if (Function.Call <bool>(Hash.IS_PED_FACING_PED, citizen.Ped, Character, MaxWitnessDistance)) { if (Helpers.IsValid(citizen.Ped.CurrentVehicle)) { if (citizen.Ped.CurrentVehicle.Model.IsHelicopter) { ray = World.Raycast(citizen.Ped.CurrentVehicle.Position + new Vector3(0, 0, -10f), Character.Position, IntersectFlags.Everything); } else { ray = World.Raycast(citizen.Ped.CurrentVehicle.Position + new Vector3(0, 0, 10 * 1.1f), Character.Position, IntersectFlags.Everything); // citizen.Ped.CurrentVehicle.Model.GetDimensions().Z * 1.1f } } else { ray = World.Raycast(citizen.Ped.Position + new Vector3(0, 0, 5), Character.Position, IntersectFlags.Everything); // citizen.Ped.Model.GetDimensions().Z } } if (ray.HitEntity != null && ((Helpers.IsValid(Character.CurrentVehicle) && ray.HitEntity.Handle == Character.CurrentVehicle.Handle) || ray.HitEntity.Handle == Character.Handle)) { GetRecognitionPercent(citizen.Ped, Character, citizen); } else { citizen.Recognition = 0; citizen.VehicleRecognition = 0; } CalcSpotted(citizen); if (Math.Max(citizen.Spotted, citizen.VehicleSpotted) <= 0) { //citizen.Ped.CurrentBlip.Remove(); Citizens.Remove(citizen); } } // Cops for (int i = Cops.Count - 1; i >= 0; i--) { Witness cop = Cops[i]; if (!cop.Ped.IsAlive) { //cop.Ped.CurrentBlip.Remove(); Cops.Remove(cop); continue; } RaycastResult ray = new RaycastResult(); if (Function.Call <bool>(Hash.IS_PED_FACING_PED, cop.Ped, Character, MaxWitnessDistance)) { if (Helpers.IsValid(cop.Ped.CurrentVehicle)) { if (cop.Ped.CurrentVehicle.Model.IsHelicopter) { ray = World.Raycast(cop.Ped.CurrentVehicle.Position + new Vector3(0, 0, -10f), Character.Position, IntersectFlags.Everything); } else { ray = World.Raycast(cop.Ped.CurrentVehicle.Position + new Vector3(0, 0, 10 * 1.1f), Character.Position, IntersectFlags.Everything); // cop.Ped.CurrentVehicle.Model.GetDimensions().Z * 1.1f } } else { ray = World.Raycast(cop.Ped.Position + new Vector3(0, 0, 5), Character.Position, IntersectFlags.Everything); // citizen.Ped.Model.GetDimensions().Z } } if (ray.HitEntity != null && ((Helpers.IsValid(Character.CurrentVehicle) && ray.HitEntity.Handle == Character.CurrentVehicle.Handle) || ray.HitEntity.Handle == Character.Handle)) { GetRecognitionPercent(cop.Ped, Character, cop); } else { cop.Recognition = 0; cop.VehicleRecognition = 0; } CalcSpotted(cop); if (Math.Max(cop.Spotted, cop.VehicleSpotted) <= 0) { //cop.Ped.CurrentBlip.Remove(); Cops.Remove(cop); } } List <Ped> NearbyPeds = new List <Ped>(); if (Citizens.Count < MaxCitizenWitnesses || Cops.Count < MaxCopWitnesses) { NearbyPeds = new List <Ped>(World.GetNearbyPeds(Character, MaxWitnessDistance)); NearbyPeds = NearbyPeds.OrderByDescending(Ped => (Character.Position - Ped.Position).Length()).ToList(); foreach (Ped ped in NearbyPeds) { // We have enough witnesses now if (Citizens.Count >= MaxCitizenWitnesses && Cops.Count >= MaxCopWitnesses) { break; } if (!ped.IsAlive || !ped.IsHuman) { continue; } // Don't add a ped we are already tracking if (Citizens.FindIndex(Citizen => Citizen.Ped.Handle == ped.Handle) > -1 || Cops.FindIndex(Cop => Cop.Ped.Handle == ped.Handle) > -1) { continue; } bool IsCop = Helpers.PedCopTypes.Contains(Function.Call <int>(Hash.GET_PED_TYPE, ped)); if ((!IsCop && Citizens.Count >= MaxCitizenWitnesses) || (IsCop && Cops.Count >= MaxCopWitnesses)) { continue; } // Only track cops right now if (!IsCop) { continue; } RaycastResult ray = new RaycastResult(); if (Function.Call <bool>(Hash.IS_PED_FACING_PED, ped, Character, MaxWitnessDistance)) { if (Helpers.IsValid(ped.CurrentVehicle)) { if (ped.CurrentVehicle.Model.IsHelicopter) { ray = World.Raycast(ped.CurrentVehicle.Position + new Vector3(0, 0, -10f), Character.Position, IntersectFlags.Everything); } else { ray = World.Raycast(ped.CurrentVehicle.Position + new Vector3(0, 0, 10 * 1.1f), Character.Position, IntersectFlags.Everything); // cop.Ped.CurrentVehicle.Model.GetDimensions().Z * 1.1f } } else { ray = World.Raycast(ped.Position + new Vector3(0, 0, 5), Character.Position, IntersectFlags.Everything); // ped.Model.GetDimensions().Z } } if (ray.HitEntity != null && ((Helpers.IsValid(Character.CurrentVehicle) && ray.HitEntity.Handle == Character.CurrentVehicle.Handle) || ray.HitEntity.Handle == Character.Handle)) { if (IsCop) { Witness NewWitness = new Witness { Ped = ped }; Cops.Add(NewWitness); if (ShowBlips) { ped.AddBlip(); //ped.CurrentBlip.Color = BlipColor.Blue; } } else { Witness NewWitness = new Witness { Ped = ped }; Citizens.Add(NewWitness); if (ShowBlips) { ped.AddBlip(); //ped.CurrentBlip.Color = BlipColor.White; } } } } } //Stopwatch.Stop(); //UI.ShowSubtitle("Witnesses: " + Witnesses.Citizens.Count + " ~b~" + Witnesses.Cops.Count + "~w~ Peds: " + NearbyPeds.Count + " CPU: " + Stopwatch.Elapsed); }
public TransactionInput Clone() { return(new(PreviousTransaction, PreviousIndex, SigScript.Clone(), Witness.Clone(), Sequence)); }
private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out uint timestampVal, out uint indexVal, out ulong consensusDataVal, out Witness scriptVal) { bb.PrevHash = val256; merkRootVal = new UInt256(new byte[] { 214, 87, 42, 69, 155, 149, 217, 19, 107, 122, 113, 60, 84, 133, 202, 112, 159, 158, 250, 79, 8, 241, 194, 93, 215, 146, 103, 45, 43, 215, 91, 251 }); bb.MerkleRoot = merkRootVal; timestampVal = new DateTime(1968, 06, 01, 0, 0, 0, DateTimeKind.Utc).ToTimestamp(); bb.Timestamp = timestampVal; indexVal = 0; bb.Index = indexVal; consensusDataVal = 30; bb.ConsensusData = consensusDataVal; val160 = UInt160.Zero; bb.NextConsensus = val160; scriptVal = new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSHT } }; bb.Witness = scriptVal; }
private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal) { bb.PrevHash = val256; merkRootVal = UInt256.Parse("0x6226416a0e5aca42b5566f5a19ab467692688ba9d47986f6981a7f747bba2772"); bb.MerkleRoot = merkRootVal; timestampVal = new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc).ToTimestampMS(); // GMT: Sunday, June 1, 1980 12:00:01.001 AM bb.Timestamp = timestampVal; indexVal = 0; bb.Index = indexVal; val160 = UInt160.Zero; bb.NextConsensus = val160; scriptVal = new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSH1 } }; bb.Witness = scriptVal; }
public async Task HandleCollectionsAsync <TCollection, TElement>(TCollection collection, int bufferSize, Witness <TElement> elementType) { _ = elementType; // only needed by Xunit to inject the right TElement type parameter var options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; await PerformSerialization <TCollection, TElement>(collection, options); options = new JsonSerializerOptions(options) { ReferenceHandler = ReferenceHandler.Preserve }; await PerformSerialization <TCollection, TElement>(collection, options); }
public static void SetupBlockWithValues(Block block, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal, out Transaction[] transactionsVal, int numberOfTransactions) { setupBlockBaseWithValues(block, val256, out merkRootVal, out val160, out timestampVal, out indexVal, out scriptVal); transactionsVal = new Transaction[numberOfTransactions]; if (numberOfTransactions > 0) { for (int i = 0; i < numberOfTransactions; i++) { transactionsVal[i] = TestUtils.GetTransaction(); } } block.ConsensusData = new ConsensusData(); block.Transactions = transactionsVal; }
public static void ApplyWitnessProperties(Witness w, WitnessData data) { w.IsCompliant = data.IsCompliant; }
internal static bool VerifyWitness(this IVerifiable verifiable, ProtocolSettings settings, DataCache snapshot, UInt160 hash, Witness witness, long gas, out long fee) { fee = 0; Script invocationScript; try { invocationScript = new Script(witness.InvocationScript, true); } catch (BadScriptException) { return(false); } using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.CreateSnapshot(), null, settings, gas)) { if (witness.VerificationScript.Length == 0) { ContractState cs = NativeContract.ContractManagement.GetContract(snapshot, hash); if (cs is null) { return(false); } ContractMethodDescriptor md = cs.Manifest.Abi.GetMethod("verify", -1); if (md?.ReturnType != ContractParameterType.Boolean) { return(false); } engine.LoadContract(cs, md, CallFlags.ReadOnly); } else { if (NativeContract.IsNative(hash)) { return(false); } if (hash != witness.ScriptHash) { return(false); } Script verificationScript; try { verificationScript = new Script(witness.VerificationScript, true); } catch (BadScriptException) { return(false); } engine.LoadScript(verificationScript, initialPosition: 0, configureState: p => { p.CallFlags = CallFlags.ReadOnly; p.ScriptHash = hash; }); } engine.LoadScript(invocationScript, configureState: p => p.CallFlags = CallFlags.None); if (engine.Execute() == VMState.FAULT) { return(false); } if (!engine.ResultStack.Peek().GetBoolean()) { return(false); } fee = engine.GasConsumed; } return(true); }
internal static bool VerifyWitness(this IVerifiable verifiable, DataCache snapshot, UInt160 hash, Witness witness, long gas, out long fee) { fee = 0; using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.CreateSnapshot(), null, gas)) { CallFlags callFlags = !witness.VerificationScript.IsStandardContract() ? CallFlags.ReadStates : CallFlags.None; byte[] verification = witness.VerificationScript; if (verification.Length == 0) { ContractState cs = NativeContract.ContractManagement.GetContract(snapshot, hash); if (cs is null) { return(false); } ContractMethodDescriptor md = cs.Manifest.Abi.GetMethod("verify", -1); if (md?.ReturnType != ContractParameterType.Boolean) { return(false); } engine.LoadContract(cs, md, callFlags); } else { if (NativeContract.IsNative(hash)) { return(false); } if (hash != witness.ScriptHash) { return(false); } engine.LoadScript(verification, initialPosition: 0, configureState: p => { p.CallFlags = callFlags; p.ScriptHash = hash; }); } engine.LoadScript(witness.InvocationScript, configureState: p => p.CallFlags = CallFlags.None); if (NativeContract.IsNative(hash)) { try { engine.StepOut(); engine.Push("verify"); } catch { } } if (engine.Execute() == VMState.FAULT) { return(false); } if (!engine.ResultStack.Peek().GetBoolean()) { return(false); } fee = engine.GasConsumed; } return(true); }
public void TestSetup() { uut = new Witness(); }
public static SignedTransaction Unserialize(BinaryReader reader) { var tx = new SignedTransaction { Type = (TransactionType)reader.ReadByte(), Version = reader.ReadByte() }; switch (tx.Type) { case TransactionType.InvocationTransaction: { //todo break; } case TransactionType.MinerTransaction: { //todo break; } case TransactionType.ClaimTransaction: { var len = (int)reader.ReadVarInt(0x10000000); tx.References = new SignedTransaction.Input[len]; for (var i = 0; i < len; i++) { tx.References[i] = UnserializeTransactionInput(reader); } break; } case TransactionType.ContractTransaction: { break; } case TransactionType.PublishTransaction: { //todo break; } case TransactionType.EnrollmentTransaction: { //todo break; } case TransactionType.RegisterTransaction: { //todo break; } case TransactionType.IssueTransaction: { break; } case TransactionType.StateTransaction: break; default: { throw new NotImplementedException(); } } var attrCount = (int)reader.ReadVarInt(16); if (attrCount != 0) { tx.Attributes = new TransactionAttribute[attrCount]; for (var i = 0; i < attrCount; i++) { tx.Attributes[i] = TransactionAttribute.Unserialize(reader); } } var inputCount = (int)reader.ReadVarInt(); tx.Inputs = new SignedTransaction.Input[inputCount]; for (var i = 0; i < inputCount; i++) { tx.Inputs[i] = UnserializeTransactionInput(reader); } var outputCount = (int)reader.ReadVarInt(); tx.Outputs = new SignedTransaction.Output[outputCount]; for (var i = 0; i < outputCount; i++) { tx.Outputs[i] = UnserializeTransactionOutput(reader); } var witnessCount = (int)reader.ReadVarInt(); tx.Witnesses = new Witness[witnessCount]; for (var i = 0; i < witnessCount; i++) { tx.Witnesses[i] = Witness.Unserialize(reader); } return(tx); }
public static void SetupHeaderWithValues(Header header, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal) { header.PrevHash = val256; header.MerkleRoot = merkRootVal = UInt256.Parse("0x6226416a0e5aca42b5566f5a19ab467692688ba9d47986f6981a7f747bba2772"); header.Timestamp = timestampVal = new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc).ToTimestampMS(); // GMT: Sunday, June 1, 1980 12:00:01.001 AM header.Index = indexVal = 0; header.NextConsensus = val160 = UInt160.Zero; header.Witness = scriptVal = new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSH1 } }; }
// claim from contract, without having private key public Transaction ClaimGas(KeyPair ownerKey, UInt160 fromScripthash, byte[] verificationScript) { var check = verificationScript.ToScriptHash(); if (check != fromScripthash) { throw new ArgumentException("Invalid verification script"); } decimal amount; var claimable = GetClaimable(fromScripthash, out amount); var references = new List <Transaction.Input>(); foreach (var entry in claimable) { references.Add(new Transaction.Input() { prevHash = entry.hash, prevIndex = entry.index }); } if (amount <= 0) { throw new ArgumentException("No GAS to claim at this address"); } List <Transaction.Input> inputs; List <Transaction.Output> outputs; GenerateInputsOutputs(ownerKey, "GAS", null, out inputs, out outputs); outputs.Add( new Transaction.Output() { scriptHash = fromScripthash, assetID = NeoAPI.GetAssetID("GAS"), value = amount }); Transaction tx = new Transaction() { type = TransactionType.ClaimTransaction, version = 0, script = null, gas = -1, claimReferences = references.ToArray(), inputs = inputs.ToArray(), outputs = outputs.ToArray(), }; var witness = new Witness { invocationScript = ("0014" + ownerKey.address.AddressToScriptHash().ByteToHex()).HexToBytes(), verificationScript = verificationScript }; tx.Sign(ownerKey, new Witness[] { witness }); var ok = SendTransaction(tx); return(ok ? tx : null); }
public static void OnPlayerWeaponShot(Vector3 targetPos, Player target, CancelEventArgs cancel) { var crime = GetCrime(target); Witness.AddCrimeCommitted(crime); }
public bool IsMasked(Witness witness) { Contract.Requires(witness != null); return false; }