Open-Transactions  0.93.0-ge03d287
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
OTSmartContract.cpp
Go to the documentation of this file.
1 /************************************************************
2  *
3  * OTSmartContract.cpp
4  *
5  * OTSmartContract is derived from OTCronItem.
6  * It handles re-occuring, (scriptable) smart contracts.
7  *
8  */
9 
10 /************************************************************
11  -----BEGIN PGP SIGNED MESSAGE-----
12  Hash: SHA1
13 
14  * OPEN TRANSACTIONS
15  *
16  * Financial Cryptography and Digital Cash
17  * Library, Protocol, API, Server, CLI, GUI
18  *
19  * -- Anonymous Numbered Accounts.
20  * -- Untraceable Digital Cash.
21  * -- Triple-Signed Receipts.
22  * -- Cheques, Vouchers, Transfers, Inboxes.
23  * -- Basket Currencies, Markets, Payment Plans.
24  * -- Signed, XML, Ricardian-style Contracts.
25  * -- Scripted smart contracts.
26  *
27  * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
28  *
29  * EMAIL:
31  *
32  * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
33  *
34  * KEY FINGERPRINT (PGP Key in license file):
35  * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
36  *
37  * OFFICIAL PROJECT WIKI(s):
38  * https://github.com/FellowTraveler/Moneychanger
39  * https://github.com/FellowTraveler/Open-Transactions/wiki
40  *
41  * WEBSITE:
42  * http://www.OpenTransactions.org/
43  *
44  * Components and licensing:
45  * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
46  * -- otlib.........A class library.......LICENSE:...LAGPLv3
47  * -- otapi.........A client API..........LICENSE:...LAGPLv3
48  * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
49  * -- otserver......Server Application....LICENSE:....AGPLv3
50  * Github.com/FellowTraveler/Open-Transactions/wiki/Components
51  *
52  * All of the above OT components were designed and written by
53  * Fellow Traveler, with the exception of Moneychanger, which
54  * was contracted out to Vicky C ([email protected]).
55  * The open-source community has since actively contributed.
56  *
57  * -----------------------------------------------------
58  *
59  * LICENSE:
60  * This program is free software: you can redistribute it
61  * and/or modify it under the terms of the GNU Affero
62  * General Public License as published by the Free Software
63  * Foundation, either version 3 of the License, or (at your
64  * option) any later version.
65  *
66  * ADDITIONAL PERMISSION under the GNU Affero GPL version 3
67  * section 7: (This paragraph applies only to the LAGPLv3
68  * components listed above.) If you modify this Program, or
69  * any covered work, by linking or combining it with other
70  * code, such other code is not for that reason alone subject
71  * to any of the requirements of the GNU Affero GPL version 3.
72  * (==> This means if you are only using the OT API, then you
73  * don't have to open-source your code--only your changes to
74  * Open-Transactions itself must be open source. Similar to
75  * LGPLv3, except it applies to software-as-a-service, not
76  * just to distributing binaries.)
77  *
78  * Extra WAIVER for OpenSSL, Lucre, and all other libraries
79  * used by Open Transactions: This program is released under
80  * the AGPL with the additional exemption that compiling,
81  * linking, and/or using OpenSSL is allowed. The same is true
82  * for any other open source libraries included in this
83  * project: complete waiver from the AGPL is hereby granted to
84  * compile, link, and/or use them with Open-Transactions,
85  * according to their own terms, as long as the rest of the
86  * Open-Transactions terms remain respected, with regard to
87  * the Open-Transactions code itself.
88  *
89  * Lucre License:
90  * This code is also "dual-license", meaning that Ben Lau-
91  * rie's license must also be included and respected, since
92  * the code for Lucre is also included with Open Transactions.
93  * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
94  * The Laurie requirements are light, but if there is any
95  * problem with his license, simply remove the Lucre code.
96  * Although there are no other blind token algorithms in Open
97  * Transactions (yet. credlib is coming), the other functions
98  * will continue to operate.
99  * See Lucre on Github: https://github.com/benlaurie/lucre
100  * -----------------------------------------------------
101  * You should have received a copy of the GNU Affero General
102  * Public License along with this program. If not, see:
103  * http://www.gnu.org/licenses/
104  *
105  * If you would like to use this software outside of the free
106  * software license, please contact FellowTraveler.
107  * (Unfortunately many will run anonymously and untraceably,
108  * so who could really stop them?)
109  *
110  * DISCLAIMER:
111  * This program is distributed in the hope that it will be
112  * useful, but WITHOUT ANY WARRANTY; without even the implied
113  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
114  * PURPOSE. See the GNU Affero General Public License for
115  * more details.
116 
117  -----BEGIN PGP SIGNATURE-----
118  Version: GnuPG v1.4.9 (Darwin)
119 
120  iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
121  vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
122  KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
123  aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
124  LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
125  sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
126  oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
127  TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
128  x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
129  nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
130  M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
131  kamH0Y/n11lCvo1oQxM+
132  =uSzz
133  -----END PGP SIGNATURE-----
134  **************************************************************/
135 
136 // OTSmartContract is derived from OTCronItem.
137 //
138 // WHAT DOES IT DO?
139 //
140 // 1) The clauses and bylaws can be written in script language by
141 // the users, without having to change OT itself. SCRIPTABLE CLAUSES!
142 // Invent your own financial instruments and processes, involving
143 // multiple agents and asset accounts.
144 // 2) Any number of parties can sign these contracts.
145 // 3) Each Party has a name, and can be referred to using that name
146 // from within the script code. Parties can also bring accounts and
147 // other assets into these agreements, and scripts can manipulate them.
148 // 4) A party to an agreement can be an individual nym, OR it can be a
149 // fictional ENTITY formed by some prior agreement.
150 // 5) A party may have many agents. Since some parties are fictional
151 // entities (e.g. a corporation, a democracy, an estate for a deceased
152 // person, etc), parties are able to appoint agents to act on their
153 // behalf. An individual Nym is really just an individual Party who
154 // acts as his own agent, whereas a corporation is owned by a voting group,
155 // and appoints a Nym to act as its agent. Voting groups will soon also be
156 // able to act as agents IN SOME RESPECTS. (Voting groups are coming
157 // next, after smart contracts.) These will be able to edit bylaws, etc.
158 // 6) A Smart Contract has a list of parties, each with a list of agents.
159 // Parties also bring asset accounts to the agreement, for use in the
160 // scripts.
161 // 7) A Smart Contract also has a list of bylaws, each with a list of clauses.
162 // Each set of Bylaws also has its own variables, which can be used by the
163 // scripts.
164 // 8) A Smart Contract can be activated (provided all parties have properly
165 // signed), and it can process repeatedly over time until it expires or gets
166 // deactivated. While it's active, parties can trigger specific clauses and
167 // the smart contract will also occasionally trigger AUTOMATICALLY (depending
168 // on how it has been configured.)
169 // 9) Users can decide which functions will activate--and when--and which
170 // powers will be vested in the various parties and agents.
171 // 10) HOOKS -- Scripts trigger upon various EVENTS such as onActivate,
172 // onDeactivate, onTrigger, etc. Perhaps a timer is set causing the custom
173 // function "TransferEmergencyFunds" to trigger in 24 hours, or 30 days,
174 // or when the price of gold reaches X... or however you code the scripted
175 // clauses in your contract...
176 //
177 // The design makes it easy to swap in different script languages. (Currently
178 // for experimental purposes I am using chaiscript.)
179 //
180 
181 /*
182  RUNNING LIST of standard hooks, functions, constants, variables, etc..
183 
184  - I'm thinking that Constants and Variables should be available in OTBylaw AND
185 OTScriptable.
186  - Ah maybe just have them in Bylaws only, and then have a "library" Bylaw that
187 is "global" to the OTScriptable.
188 
189  - OT Internal Functions will be available on server side inside scripts, just
190 like OT API is
191  on client side. They're written in C++.
192  - Callbacks are the opposite: they're written in script, and available for the
193 C++ to call when it needs to.
194  - Script Functions can be called by all parties, unless CanTriggerClause(name,
195 party) returns false.
196  - Hooks should be stored as a list on the Bylaws. If hook "OnActivate" is
197 triggered, then I ask each Bylaw to
198  run any relevant scripts for that hook.
199 
200 
201  VARIABLES (These are changed values you can store inside your smart contract,
202 which stay persistent between runs.)
203 
204  -- The first one of these will probably be a timer variable, used with
205 OnProcess() to trigger some
206  timed clause. You'll set it to 100, then decrement every call, then trigger
207 when it hits zero.
208  (Or trigger every time X person withdraws money, etc.)
209 
210  -- Let's say a contract processes 100 times but only does something important
211 the last time. Do I REALLY
212  need a receipt for every fucking 100 times just because some timer variable
213 changed? Therefore, probably
214  want to strictly define two types of variables: Those that require a
215 receipt when they change, and those
216  that do not. Therefore:
217 
218  TYPES: Constant (cannot change), Persistent (stores over time; change doesn't
219 require noticing the parties),
220  Important (Stores over time; change requires notice to the parties).
221 
222  Any notice should be accompanied by a notice # so parties can see if they
223 missed a notice.
224 
225  ------------------------------------------------------------------------
226 
227 
228  CONSTANTS (These are standard values available inside any script.)
229 
230  -- ProcessInterval. (The contract will activate every X seconds. Default 30.)
231 
232  NOTE: I probably won't let users change this, but rather, will let them
233  use a multiple of it. Or maybe I'll let them have fine-tuned timing, but just
234  charge them for it via server fees.
235 
236  ------------------------------------------------------------------------
237 
238  CALLBACKS (OT will call these scripts when it needs an answer to something.)
239 
240  -- CanDeactivate(Party). Script returns true/false whether Party is allowed to
241 deactivate the contract.
242  Anyone party to the contract can cancel it, by default. (You can change that
243 with this callback.)
244 
245  can_execute_clause(party_name, clause_name)
246 
247  -- CanTriggerClause(Party, Clause). Script returns whether Party is allowed to
248 call this clause. Default true.
249 
250  ------------------------------------------------------------------------
251 
252  OT INTERNAL FUNCTIONS (Calls into OT that you can make from inside your
253 scripts.)
254 
255  -- These are like the OT API calls, except on the server side. Examples?
256 
257  -- ExecuteClause(Bylaw, Clause)
258  -- ExecuteClause(Clause)
259 
260  These allow you to, from inside a clause, execute any other clause on the
261 same contract.
262 
263  -- FlagForRemoval() This removes the script from Cron. Deactivates it.
264 
265  -- Imagine OTParty->SendMessage(OtherParty). CANNOT DO THIS. Why not? Because
266 on the client side, the sender
267  can actually sign the thing before sending it. But on the server side, the
268 server cannot sign with someone's
269  nym since it doesn't have that private key. It CAN verify contracts, and
270 transfer money, check balances, etc.
271 
272  -- Definitely a call that transfers money from one Party's account to another,
273 dropping a receipt.
274 
275  -- Calls that withdraw money and return a financial instrument. For example:
276 "Take 100 clams out of Jim's acct,
277  issue a server cheque for 100 clams, and send it to George." You might ask,
278 why not just have the cheque come
279  from Jim directly? Answer: Because the server can't forge Jim's signature.
280 Instead, the server justifies the
281  action to Jim by providing a copy of the script contract in his inbox
282 receipt when it takes the money. It signs
283  its own cheque, which is something it actually can do, and it sends it to
284 George. A copy is sent to all parties
285  so they can prove later on whether the voucher was redeemed. But they can't
286 redeem it themselves, since it is
287  made out to George.
288 
289  -- Interesting: Certain instruments REQUIRE the client side! The server can't
290 withdraw cash on your behalf since
291  it can't generate the prototokens, nor can it unblind them. The server can't
292 write a cheque on your behalf since
293  it can't forge your signature. It CAN withdraw cash on its own, and send to
294 whoever you want, but then you have
295  to trust the server not trace that cash (it's traceable in that case.) It
296 CAN write a cheque on your behalf, but
297  of course you have to trust the server that the money will be there when
298 that cheque is cashed. It CANNOT create
299  a market order on your behalf! You have to sign that when you do it. It
300 CANNOT activate some new smart contract
301  on your behalf, since it can't forge your signature. It CANNOT initiate a
302 transfer (since you must sign.) Instead
303  it just moves the funds and leaves you a copy of the script as your receipt.
304 (You DID sign the script, so it IS
305  a good enough receipt for that.) I suppose that it CAN exchange you in/out
306 of a basket, although normally you'd
307  expect a receipt showing your request. I guess future versions of OT can be
308 smart enough to interpret a basket
309  receipt in different ways, depending on whether the InRefTo contains an
310 exchange request or a smart contract.
311 
312  -- A call that ADDS a script to a hook. Imagine there 100 different hooks: you
313 don't actually have scripts for
314  all of them!!! But perhaps you have a certain script, that gets ATTACHED to
315 a hook at some point, based on
316  script logic, and then THEREAFTER activates on that hook when it previously
317 didn't. Therefore even OnActivate()
318  and OnDeactivate() should have their own actual script names, and then those
319 scripts are attached to the hooks
320  known as OnActivate and OnDeactivate(). The portion of the smart contract
321 that attaches them changes over time,
322  as this call is made, adding them and removing them.
323  It could be that ONE script is registered to a hook, and then some event
324 causes it to be de-registered
325  and then another one is registered to take its place!
326 
327  -- Functions to send notices to various parties and inboxes. (The server can't
328 forge a party's message to
329  another, but it CAN send them all a message from the server itself.)
330 Therefore NOTICES.
331 
332  -- Anytime funds are moved between accounts, they should get a scriptReceipt
333 aka paymentReceipt type deal.
334 
335  ------------------------------------------------------------------------
336 
337  SCRIPT FUNCTIONS (Scripts you add to your smart contract, which can be
338 triggered by parties.)
339 
340  -- First one will probably be "DisputeEscrow()" for the escrow contract.
341 
342  -- Might be nice to have clauses that are available for others to call.
343  Perhaps a "library" Bylaw that other bylaws have access to.
344 
345  ------------------------------------------------------------------------
346 
347  HOOKS (Scripts you add to your smart contract, which will trigger
348 automatically upon specific events.)
349 
350  -- OnActivate() This happens when script is first activated.
351  -- OnDeactivate() This happens when script is deactivated.
352  -- OnProcess() This happens every ProcessInterval.
353  -- OnExpire() Happens when the script is deactivated due to reaching
354 end of valid date/time range.
355 
356 
357 
358  OTHER HOOKS?
359 
360 
361  Bylaws need to have a list of hooks, where the hook name corresponds to the
362 clause name.
363  Just as they have a list of clauses, they also need a list of the hooks those
364 clauses are triggered by.
365 
366 
367 
368 
369 
370 
371  Still need todo on smart contracts:
372 
373  -- Serialization
374  -- Confirmation
375  -- Verification
376  -- Native Functions such as:
377 
378  move_funds(from_acct, to_acct) (from_acct and to_acct must be
379 a party to the agreement)
380  send_cashiers_cheque(from_acct, to_nym) (from_acct must be a party to
381 the agreement. to_nym doesn't have to be.)
382  stash_funds(from_acct, "stash_one", 100) ("stash_one" is stored inside
383 the bylaw. Server-side only.)
384  unstash_funds("stash_one", to_acct, 100) (Smartcontract must be activated
385 with no stashes. Server creates/maintains them.)
386  unstash_funds_to_nym("stash_one", to_nym, 100) (This is like
387 send_cashiers_cheque, except from a stash.)
388  get_balance(acct) (acct must be party to
389 agreement.)
390 
391  send_notice(to_nym) (Like sendMessage, except it
392 comes from the server, not another user.)
393  send_notice_to_parties() (Does a send_notice to ALL
394 parties.)
395 
396  can_execute_clause(party_name, clause_name) (See if a party is allowed to
397 execute any given clause.)
398 
399 
400  -- Dirtiness:
401  Important variables changed require a Nymbox notice sent. (agreementReceipt)
402  Any movement of funds requires Inbox notice sent to relevant parties. (can I
403 just use paymentReceipt? Otherwise agreementReceipt here too.)
404  FinalReceipt requires Nymbox AND Inbox notices to be sent. (finalReceipt.)
405 
406  -- Client command to message server and activate a new SmartContract.
407  -- Server functions to process said message, and activate the script on cron.
408 
409  -- (Postponed) Make a new OTScriptable-derived class called OTTitle (which
410 represents a registered piece of property)
411  and add client commands / server functions for functionality like
412 SmartContract, except you are registering an
413  OTTitle for a static piece of property, versus activating an OTCronItem that
414 processes and triggers repeatedly
415  over time. OTTitle will probably derive from OTContract, in the same way
416 that OTAssetContract derives from
417  OTContract. You will be able to register title on a server similar to
418 registering an asset contract. Except,
419  instead of getting an issuer acct, you get a deed...
420 
421  -- (Postponed) There are several ways to own title to property. One is to have
422 an OTDeed class, which allows any specific Nym to
423  have a title registered to him based on a specific transaction #, which is
424 released whenever the deed is transferred.
425  This enables destruction-of-acct-history similar to unit-based accounts, but
426 it also necessitates the use of an "asset
427  account" (with an inbox) specifically for holding deed-based property. (This
428 is necessary in order to prove ownership
429  and everything else--the same as with unit-based accounts.) I probably will
430 NOT code this "deed" piece anytime soon...
431 
432  -- (Upcoming) ...HOWEVER, ANOTHER WAY to own title (WITHOUT A DEED) is through
433 SHAREHOLDING. That is where my interest currently
434  lies. Therefore I will add the OTEntity class. Instead of being derived from
435 OTContract like OTTitle, it will be derived from
436  OTScriptable (similar to the smart contracts.) This will enable it to have
437 parties and bylaws.
438  Similar to cron items, which save the original copy but also save updated
439 copies whenever something changes, I will cause
440  OTEntity to generate a unique ID based on the entity as it originally
441 appeared when first registered. The original version
442  is always retrievable by a shareholder and hashing it should produce the
443 actual entity ID.
444  But from there, the Entity can evolve over time. Since it is
445 OTScriptable-derived, it can have parties, and bylaws. The
446  parties can take actions to change the bylaws and appointments.
447  The political structure of the entity is determined by the parties. There
448 might be 3 parties who are all Nyms, in which case
449  you have a partnership. If the entity's charter says, "Party A is a Nym:
450 FellowTraveler", and if all parties by default have
451  the power to alter the bylaws, appoint employees, activate clauses to move
452 funds, etc, then you now have an individual
453  controlling the entity.
454  WHERE THIS IS GOING: A party whose agent is a voting group, whose members
455 are determined by shareholdership in STOCK of
456  the entity. (Really could be configured to stock in any stock ID, but people
457 will WANT the stock to be in the entity.) Future
458  versions of OT will allow creation of multiple classes of stock, and indeed
459 there is nothing stopping entities now from
460  issuing whatever currencies they want, with the issuer accounts controlled
461 by them or their agents. Of course it's better
462  to have it strict in the bylaws, and have OT just execute it that way, and
463 for now that's how it will be with the DEFAULT,
464  HARDCODED current path of a SINGLE class of stock for each entity, with the
465 Entity's ID serving as the Asset Type ID. I think
466  it would be a LONG TIME before we ever need more functionality than that
467 anyway, so that's what I'll focus on.
468 
469  -- So I need OTVotingGroup class which will determine members based on various
470 types of groups.
471  1) Shareholders. Expects a weighted vote among shareholders based on asset
472 type ID matching entity ID.
473  2) Appointed members. A list of members (NymIDs) is explicitly stored in
474 this group. (Like the list of board members.)
475 
476  (1) Will take advantage of existing asset account code (for weighted
477 voting),
478  and (2) will take advantage of existing digital cash code (for secret
479 ballots.)
480 
481  For both types of groups, votes will be possible such as Majority rules,
482 2/3rds, 3/4ths, 9/10ths, Unanimous, etc.
483  In the case of appointed members (2), permissions can be granted to members,
484 such as dictator, dictator subject to veto,
485  veto power, etc etc. In this way, democracies, republics, corporations, etc
486 all become possible through simple config changes.
487 
488  But all of the actual voting will not happen until I code classes like
489 OTBallot, OTElection, etc. That's not my current
490  focus. We will get to that in time. Rather, my focus is on the use of
491 SHAREHOLDERS to allow weighted, account-based ownership
492  of STOCK in ENTITIES. My interest right now is on the ENTITIES THEMSELVES,
493 and their ability to be party to agreements, and
494  to hire employees, and to own property and asset accounts.
495 
496  So an EntityID is similar to a TitleID, in the sense that an entity is a
497 piece of property that can be owned. But an EntityID
498  is also similar to an AssetTypeID, since there can be a currency issued for
499 that entity. And an entity is also similar to a smart
500  contract, in the sense that it can have bylaws, and it can have "parties to
501 the agreement".
502 
503  Beyond that, entities will also have the ability to hire employees, sign
504 contracts, own property, etc. Distribute funds up and
505  down the hierarchy, and have access the communications and receipts up and
506 down the hierarchy.
507 
508  -- Entity will not be derived from a Title, because they are fundamentally
509 different enough. Entities are owned by the voting groups
510  that make them up, according to their laws. Whereas Titles are owned based
511 on holder of Deed.
512 
513  -- Therefore, NOT needed for now: OTTitle, OTDeed, OTBallot, OTElection.
514 
515  -- NEEDED and coming soon: OTVotingGroup, OTEntity. I'll start on these once I
516 have proven the first SMART CONTRACT (Escrow!!!!!)
517 
518 
519 ===> NEW THOUGHT: I think OTAssetContract should be derived from OTScriptable
520 instead of OTContract. There's no reason why an
521  issuer shouldn't be able to attach scripts to certain aspects of a
522 currency, right? Hooks could trigger at various currency-related
523  events. There's also no reason why an issued currency shouldn't be able to
524 have parties. But who are the parties, if not the issuer?
525  In the case of OTAssetContract, the parties will be whoever are configured
526 to do whatever the clauses need them to do, which will often
527  be nothing, though technically they could be used for AUTOMATED BAILMENT
528 PROCESSES!! (Say one of the parties is a voting group consisting
529  of anyone who holds stock. And that party has the right to trigger the
530 "bailout" clause, which has the power the transfer the funds auto-
531  matically (via a script) to another party or account.) I don't know how
532 people might use this, but it seems potentially useful.
533 
534  ===> Once this is in place, then it's easy to have OTEntity be derived from
535 OTAssetContract!! And that's where we'll get our Entity ID.
536 
537  ===> ANOTHER IDEA: SHould be easy to move funds ONTO THE SMART CONTRACT
538 ITSELF. Just have an XML tag where stored funds go, perhaps with the
539  funds double in a server backing account (similar to how the cash already
540 is.) The script can enable peeps to move funds from an acct
541  and to a safe place (inside the smart contract itself) until some other
542 rule causes it to be moved somewhere else. This is needed for ESCROW!!!
543  Perhaps I'll call this a "fund". OTFund. The only other way for an
544 entity to control funds is to open accounts, meaning it must trust the
545  Nym who's been appointed to the role of managing that account. The entity
546 ITSELF can't open accounts because there is no signer!!! But the
547  entity CAN control FUNDS, because they are stored inside the entity
548 itself!! (relevant parties get receipts for changes to entities...) And
549  unlike a Nym, everyone can trust a cold, hard, script.
550 
551 
552  ===> REALIZATION: For my audit protocol, I wanted to have some kind of DHT to
553 store the receipts, where issuer and customer both have access to
554  them, but where the system itself cannot otherwise be shut down. And you
555 can't just put some IP address of a server into the contract (as the
556  location for those receipts) because then a "power that be" can read the
557 contract, and shut down the server at that IP.
558  BUT NOW, possibly the solution may somehow lie in Namecoin, which is a
559 censorship-proof DHT where I could store an I2P address. Do I still need
560  a DHT for the receipts themselves, as long as DNS is safe from
561 interference, and I can control where it points to? Since all parties (issuer
562 and
563  users) would read their receipts from the same place (whichever address is
564 listed in Namecoin) and since it's on an anonymous network, then I
565  believe the issuer and transaction server can exchange receipts in a safe
566 way. Possibly this solves any auditing issues, though I still need to
567  devise the protocol.
568  But this still means that someone is running a server somewhere, and must
569 be in order for people to get their receipts, whereas using a full DHT
570  solution is more... certifiable. notarizable. Because you have the whole
571 blockchain verifying that receipt was posted...
572 
573  Maybe the issuer just needs to demand that all receipts are numbered
574 sequentially? hm.
575 
576  ===> NEW THOUGHT: For Auditing protocol: EVERY RECEIPT for any specific asset
577 type should be sequentially numbered, AND should contain the hash of
578  the receipt that came before it. This way, the auditor can receive a
579 verifiable stream of receipts, which can also be queried by transaction #,
580  which is unique to all transactions on the transaction server, as well as
581 queried by sequence number, which is unique to the issuer, as well as
582  queried by hash value, which is used to prove sequence.
583  Every receipt should be encrypted to a random key, and then that key
584 should be encrypted to three recipients: the server, the auditor, and the
585  party doing the transaction. The receipts should otherwise be publicly
586 available (though encrypted) and auditors and parties should have to retrieve
587  them from the same place. Even if I allow the parties to keep the
588 receipts directly in response to their server messages, they can still compare
589  notes directly with the auditor and each other on the hashes for the
590 various sequence numbers. Hm.
591  */
592 
593 #include "stdafx.hpp"
594 
595 #include "OTSmartContract.hpp"
596 #include "OTAgent.hpp"
597 #include "OTBylaw.hpp"
598 #include "OTClause.hpp"
599 #include "cron/OTCron.hpp"
600 #include "util/OTFolders.hpp"
601 #include "OTLedger.hpp"
602 #include "OTLog.hpp"
603 #include "OTParty.hpp"
604 #include "OTPartyAccount.hpp"
605 #include "OTPseudonym.hpp"
606 #include "OTStash.hpp"
607 #include "OTStashItem.hpp"
608 #include "OTStorage.hpp"
609 
610 #include <irrxml/irrXML.hpp>
611 
612 #ifdef OT_USE_SCRIPT_CHAI
613 #include "OTScriptChai.hpp"
614 #include <chaiscript/chaiscript.hpp>
615 #ifdef OT_USE_CHAI_STDLIB
616 #include <chaiscript/chaiscript_stdlib.hpp>
617 #endif
618 #endif
619 
620 #include <memory>
621 
622 #ifndef SMART_CONTRACT_PROCESS_INTERVAL
623 #define SMART_CONTRACT_PROCESS_INTERVAL \
624  30 // 30 seconds, for testing. Should be: based on fees. Otherwise once per
625  // day should be enough... right?
626 #endif
627 
628 // CALLBACK: Party may cancel contract?
629 //
630 // Called in OnRemove and OnExpire,
631 // at the bottom.
632 //
633 #ifndef SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL
634 #define SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL \
635  "callback_party_may_cancel_contract"
636 #endif
637 
638 // FYI:
639 //#ifndef SCRIPTABLE_CALLBACK_PARTY_MAY_EXECUTE
640 //#define SCRIPTABLE_CALLBACK_PARTY_MAY_EXECUTE
641 //"callback_party_may_execute_clause"
642 //#endif
643 
644 // HOOKS
645 //
646 // The server will call these hooks, from time to time, and give you the
647 // opportunity to provide your own scripts linked to these names, which
648 // will trigger at those times. (Parties are normally disallowed from
649 // directly triggering these special "hook" scripts, as they might normally
650 // be allowed to trigger other clauses.)
651 //
652 
653 // Called regularly in OTSmartContract::ProcessCron()
654 // based on SMART_CONTRACT_PROCESS_INTERVAL.
655 //
656 #ifndef SMARTCONTRACT_HOOK_ON_PROCESS
657 #define SMARTCONTRACT_HOOK_ON_PROCESS "cron_process"
658 #endif
659 
660 // This is called when the contract is
661 // first activated. Todo.
662 //
663 #ifndef SMARTCONTRACT_HOOK_ON_ACTIVATE
664 #define SMARTCONTRACT_HOOK_ON_ACTIVATE "cron_activate"
665 #endif
666 
667 // Deprecated:
668 //
669 // (These hooks exist in the OT class library, and you CAN subclass
670 // OT classes to take advantage of them. But I don't see how they can
671 // be allowed from within the SCRIPT language itself, at least, not
672 // without some kinds of config options to govern the permissions.)
673 //
674 
675 // Called when a party removes the
676 // contract from processing.
677 //
678 // Update NOTE: script may not execute. Script has been removed. Sorry.
679 // (Notices are sent automatically.)
680 //
681 #ifndef SMARTCONTRACT_HOOK_ON_REMOVE
682 #define SMARTCONTRACT_HOOK_ON_REMOVE "cron_remove"
683 #endif
684 
685 // When it expires due to date range.
686 //
687 // Update NOTE: script may not execute. Script has expired. Sorry.
688 // (Notices are sent automatically.)
689 //
690 #ifndef SMARTCONTRACT_HOOK_ON_EXPIRE
691 #define SMARTCONTRACT_HOOK_ON_EXPIRE "cron_expire"
692 #endif
693 
694 // Called in OnRemove and OnExpire,
695 // at the bottom.
696 //
697 // Update NOTE: so far script may not execute. Script has been deactivated,
698 // sorry.
699 // Notices are sent automatically.
700 //
701 #ifndef SMARTCONTRACT_HOOK_ON_DEACTIVATE
702 #define SMARTCONTRACT_HOOK_ON_DEACTIVATE "cron_deactivate"
703 #endif
704 
705 namespace opentxs
706 {
707 
708 // TODO: Finish up Smart Contracts (this file.)
709 
710 // DONE: Client test code, plus server message: for activating smart contracts.
711 
712 // DONE: OT API calls for smart contracts.
713 
714 // DONE: Build escrow script.
715 
716 // TODO: Entities and roles. (AFTER smart contracts are working.)
717 
718 // TODO: Finish move_funds, which should be super easy now. The script-callable
719 // version
720 // HAS to be in OTSmartContract. Why? Because it can't be in OTScriptable, since
721 // those shouldn't
722 // be allowed to move funds (they are unlike payment plan / trades, which have
723 // an open trans#
724 // that can be put onto receipts, and a final receipt with a closing trans#,
725 // which allow recurring
726 // processing (multiple receipts for the same transaction) -- this all fits into
727 // the "destruction
728 // of acct history" system perfectly, because it's built into OTCronItem.
729 // OTScriptable isn't derived
730 // from OTCronItem, so it can't do those things, therefore it can't be allowed
731 // to move money.
732 //
733 // Fair enough. But then, why not put move_funds into OTCronItem? After all, it
734 // IS derived from
735 // OTScriptable, if you go far enough back, and so it technically can play both
736 // sides. Here's why not:
737 // Because OTTrade and OTPaymentPlan were both written before I wrote all the
738 // smart contract stuff.
739 // It was only when I added smart contracts that I finally implemented Parties,
740 // Agents, Bylaws, Clauses,
741 // etc etc. This means that the way things are done is vastly different.
742 // Therefore while OTSmartContract
743 // is derived from OTCronItem, OTSmartContract is the first Cron Item that does
744 // it the SCRIPTABLE way,
745 // whereas OTTrade and OTPaymentPlan still do it the "OTCronItem" way.
746 //
747 // For example, in OTSmartContract, the Opening Transaction # is stored ONE FOR
748 // EACH PARTY, and the
749 // Closing Transaction # is stored ONE FOR EACH ASSET ACCOUNT. You can have
750 // many many parties AND
751 // asset accounts on a smart contract. This is simply not the case for OTTrade
752 // and OTPaymentPlan. They
753 // use their own little built-in system for managing their strict system for
754 // storing the exact numbers
755 // they need. They always use the exact same number of Nyms and accounts.
756 //
757 // But smart contracts obviously do much more, so a more elegant system has been
758 // crafted into OTSmartContract
759 // which blends the best qualities of OTScriptable AND OTCronItem, and which is
760 // the only place where you can
761 // have BOTH script interpretation (from OTScriptable) AND money-moving,
762 // receipts, transactions, etc (OTCronItem).
763 //
764 // Therefore, OTCronItem already has the lower-level call to MoveFunds, which
765 // you can see commented below.
766 // And OTSmartContract will have a higher-level version that can be available
767 // inside scripts as an "OT Native call",
768 // and which searches the parties/accounts/agents etc so that it is able to then
769 // make the lower-level call.
770 // Therefore move_funds goes in OTSmartContract, and MoveFunds goes in
771 // OTCronItem.
772 //
773 //
774 //
775 
776 /*
777 CALLBACKS
778 
779 DONE party_may_cancel_contract(party_name) (See if a party is
780 allowed to cancel the contract from processing.)
781 DONE party_may_execute_clause(party_name, clause_name) (See if a party is
782 allowed to execute any given clause.)
783 
784 NATIVE CALLS
785 
786 DONE move_funds(from_acct, to_acct, amount) (from_acct and to_acct must
787 be a party to the agreement)
788 DONE stash_funds(from_acct, "stash_one", 100) ("stash_one" is stored INSIDE
789 the smartcontract! Server-side only.)
790 DONE unstash_funds(to_acct, "stash_one", 100) (Smartcontract must be
791 activated with NO stashes. Server creates/maintains stashes AFTER activation.)
792 
793 DONE get_acct_balance(acct) Returns int64_t. (Named
794 acct must be party to agreement with legitimate authorized agent.)
795 DONE get_acct_asset_type_id(acct) Returns std::string. (Named
796 acct must be party to agreement with legitimate authorized agent.)
797 DONE get_stash_balance(stash, asset_type_id) Returns int64_t. (Named
798 stash must exist.)
799 
800 DONE send_notice(to_party) (Like sendMessage, except it comes from the
801 server, not another user. Drops current state of smart contract to Nymbox of all
802 agents for party named.)
803 DONE send_notice_to_parties() (Does a send_notice to ALL parties.)
804 
805 DONE deactivate_contract() (Deactivates and finalizes the smart
806 contract.)
807 
808 HOOKS
809 
810 DONE cron_process (Triggers every time the smart contract "processes" on
811 cron.)
812 DONE cron_activate (Triggers when the smart contract is first activated.)
813 */
814 
815 // Global version. (string parameter)
816 // typedef bool (*OT_SM_RetBool_ThrStr)(OTSmartContract* pContract,
817 // const std::string from_acct_name,
818 // const std::string to_acct_name,
819 // const std::string str_Amount);
820 // Test result: WORKS calling chaiscript
821 // Cron: Processing smart contract clauses for hook: cron_process
822 // OTSmartContract::MoveAcctFunds: error: from_acct
823 // (sSBcoTlTkYY8pPv6vh2KD6mIVrRdIwodgsWDoJzIfpV) not found on any party. //
824 // debug this in move_funds
825 // OTSmartContract::ExecuteClauses: Success executing script clause:
826 // process_clause.
827 
828 // Global version. (int64_t parameter)
829 // typedef bool (*OT_SM_RetBool_TwoStr_OneL)(OTSmartContract* pContract,
830 // const std::string from_acct_name,
831 // const std::string to_acct_name,
832 // const int64_t lAmount);
833 // TEST Result: FAILS calling chaiscript: Cannot perform boxed_cast. (Must be
834 // the LONG!!)
835 // Cron: Processing smart contract clauses for hook: cron_process
836 // OTScriptChai::ExecuteScript: Caught chaiscript::exception::bad_boxed_cast :
837 // Cannot perform boxed_cast.
838 // OTSmartContract::ExecuteClauses: Error while running script: process_clause
839 
840 // Class member, with string parameter.
842  std::string from_acct_name, std::string to_acct_name,
843  std::string str_Amount);
844 
845 // TEST RESULT: WORKS calling Chaiscript
846 // Cron: Processing smart contract clauses for hook: cron_process
847 // OTSmartContract::MoveAcctFunds: error: from_acct
848 // (sSBcoTlTkYY8pPv6vh2KD6mIVrRdIwodgsWDoJzIfpV) not found on any party.
849 // OTSmartContract::ExecuteClauses: Success executing script clause:
850 // process_clause.
851 
852 // Class member, with int64_t parameter.
853 // typedef bool (OTSmartContract::*OT_SM_RetBool_TwoStr_OneL)(const std::string
854 // from_acct_name,
855 // const std::string
856 // to_acct_name,
857 // int64_t lAmount);
858 
860 {
861  // CALL THE PARENT
863 
864 #ifdef OT_USE_SCRIPT_CHAI
865  using namespace chaiscript;
866 
867  OTScriptChai* pScript = dynamic_cast<OTScriptChai*>(&theScript);
868 
869  if (nullptr != pScript) {
870  OT_ASSERT(nullptr != pScript->chai)
871 
872  // OT NATIVE FUNCTIONS
873  // (These functions can be called from INSIDE the scripted clauses.)
874  // //
875  // Parameters must match as described below. Return value will be as
876  // described below.
877  //
878  // pScript->chai->add(base_class<OTScriptable,
879  // OTSmartContract>());
880 
881  pScript->chai->add(
882  fun<OT_SM_RetBool_ThrStr>(&OTSmartContract::MoveAcctFundsStr, this),
883  "move_funds");
884 
885  pScript->chai->add(fun(&OTSmartContract::StashAcctFunds, this),
886  "stash_funds");
887  pScript->chai->add(fun(&OTSmartContract::UnstashAcctFunds, this),
888  "unstash_funds");
889  pScript->chai->add(fun(&OTSmartContract::GetAcctBalance, this),
890  "get_acct_balance");
891  pScript->chai->add(fun(&OTSmartContract::GetAssetTypeIDofAcct, this),
892  "get_acct_asset_type_id");
893  pScript->chai->add(fun(&OTSmartContract::GetStashBalance, this),
894  "get_stash_balance");
895  pScript->chai->add(fun(&OTSmartContract::SendNoticeToParty, this),
896  "send_notice");
897  pScript->chai->add(fun(&OTSmartContract::SendANoticeToAllParties, this),
898  "send_notice_to_parties");
899  pScript->chai->add(fun(&OTSmartContract::SetRemainingTimer, this),
900  "set_seconds_until_timer");
901  pScript->chai->add(fun(&OTSmartContract::GetRemainingTimer, this),
902  "get_remaining_timer");
903 
904  pScript->chai->add(fun(&OTSmartContract::DeactivateSmartContract, this),
905  "deactivate_contract");
906 
907  // CALLBACKS
908  // (Called by OT at key moments) todo security: What if these are
909  // recursive? Need to lock down, put the smack down, on these smart
910  // contracts.
911  //
912  // FYI: pScript->chai->add(fun(&(OTScriptable::CanExecuteClause),
913  // (*this)), "party_may_execute_clause"); // From OTScriptable (FYI)
914  // param_party_name and param_clause_name will be available inside
915  // script. Script must return bool.
916  // FYI: #define SCRIPTABLE_CALLBACK_PARTY_MAY_EXECUTE
917  // "callback_party_may_execute_clause" <=== THE CALLBACK WITH THIS
918  // NAME must be connected to a script clause, and then the clause will
919  // trigger when the callback is needed.
920 
921  pScript->chai->add(fun(&OTSmartContract::CanCancelContract, this),
922  "party_may_cancel_contract"); // param_party_name
923  // will be available
924  // inside script.
925  // Script must return
926  // bool.
927  // FYI: #define SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL
928  // "callback_party_may_cancel_contract" <=== THE CALLBACK WITH THIS
929  // NAME must be connected to a script clause, and then the clause will
930  // trigger when the callback is needed.
931 
932  // Callback USAGE: Your clause, in your smart contract, may have
933  // whatever name you want. (Within limits.)
934  // There must be a callback entry in the smart
935  // contract, linking your clause the the appropriate callback.
936  // The CALLBACK ENTRY uses the names
937  // "callback_party_may_execute_clause" and
938  // "callback_party_may_cancel_contract".
939  // If you want to call these from INSIDE YOUR SCRIPT,
940  // then use the names "party_may_execute_clause" and
941  // "party_may_cancel_contract".
942 
943  // HOOKS:
944  //
945  // Hooks are not native calls needing to be registered with the script.
946  // (Like the above functions are.)
947  // Rather, hooks are SCRIPT CLAUSES, that you have a CHOICE to provide
948  // inside your SMART CONTRACT.
949  // *IF* you have provided those clauses, then OT *WILL* call them, at
950  // the appropriate times. (When
951  // specific events occur.) Specifically, Hook entries must be in your
952  // smartcontract, linking the below
953  // standard hooks to your clauses.
954  //
955  // FYI: #define SMARTCONTRACT_HOOK_ON_PROCESS "cron_process"
956  // // Called regularly in OTSmartContract::ProcessCron() based on
957  // SMART_CONTRACT_PROCESS_INTERVAL.
958  // FYI: #define SMARTCONTRACT_HOOK_ON_ACTIVATE "cron_activate"
959  // // Done. This is called when the contract is first activated.
960  }
961  else
962 #endif // OT_USE_SCRIPT_CHAI
963  {
964  otErr << "OTSmartContract::RegisterOTNativeCallsWithScript: Failed "
965  "dynamic casting OTScript to OTScriptChai \n";
966  }
967 
968 } // void function
969 
970 void OTSmartContract::DeactivateSmartContract() // Called from within script.
971 {
972  // WARNING: If a party has the right to execute a clause that calls
973  // DeactivateSmartContract(),
974  // then that party can deactivate the smartcontract by calling that clause,
975  // regardless of what
976  // "CanPartyCancelClause()" says he can do.
977  // (And by default, any legitimate party can trigger any clause, at any
978  // time, unless your script
979  // override says differently.)
980 
981  otOut << "OTSmartContract::DeactivateSmartContract: deactivate_contract() "
982  "was called from within the script. "
983  "Flagging smartcontract for removal from Cron ("
984  << GetTransactionNum() << ").\n";
985 
986  FlagForRemoval(); // Remove it from future Cron processing, please.
987 }
988 
989 // These are from OTScriptable (super-grandparent-class to *this):
990 /* ----------------------------------------------------
991 OTParty * GetParty (std::string str_party_name);
992 OTBylaw * GetBylaw (std::string str_bylaw_name);
993 OTClause * GetClause (std::string str_clause_name);
994 OTParty * FindPartyBasedOnNymAsAgent(OTPseudonym& theNym, OTAgent **
995 ppAgent=nullptr);
996 OTParty * FindPartyBasedOnNymAsAuthAgent(OTPseudonym& theNym, OTAgent **
997 ppAgent=nullptr);
998 OTParty * FindPartyBasedOnAccount(OTAccount& theAccount, OTPartyAccount **
999 ppPartyAccount=nullptr);
1000 OTParty * FindPartyBasedOnNymIDAsAgent(const OTIdentifier& theNymID, OTAgent **
1001 ppAgent=nullptr);
1002 OTParty * FindPartyBasedOnNymIDAsAuthAgent(const OTIdentifier& theNymID,
1003 OTAgent ** ppAgent=nullptr);
1004 OTParty * FindPartyBasedOnAccountID(const OTIdentifier& theAcctID,
1005 OTPartyAccount ** ppPartyAccount=nullptr);
1006 OTAgent * GetAgent(std::string str_agent_name);
1007 OTPartyAccount * GetPartyAccount(std::string str_acct_name);
1008 OTPartyAccount * GetPartyAccountByID(const OTIdentifier& theAcctID);
1009 */
1010 
1011 // Returns true if it was empty (and thus successfully set.)
1012 // Otherwise, if it wasn't empty (it had been already set) then
1013 // it will fail to set in this call, and return false.
1014 //
1016 {
1017  if (GetServerID().IsEmpty()) {
1018  SetServerID(theID);
1019  return true;
1020  }
1021  return false;
1022 }
1023 
1024 bool OTSmartContract::IsValidOpeningNumber(const int64_t& lOpeningNum) const
1025 {
1026  for (const auto& it : m_mapParties) {
1027  OTParty* pParty = it.second;
1028  OT_ASSERT(nullptr != pParty);
1029 
1030  if (pParty->GetOpeningTransNo() == lOpeningNum) return true;
1031  }
1032 
1033  return false;
1034 }
1035 
1036 // Checks opening number on parties, and closing numbers on each party's
1037 // accounts.
1038 // Overrides from OTTrackable.
1039 //
1040 bool OTSmartContract::HasTransactionNum(const int64_t& lInput) const
1041 {
1042  for (const auto& it : m_mapParties) {
1043  const OTParty* pParty = it.second;
1044  OT_ASSERT(nullptr != pParty);
1045 
1046  if (pParty->HasTransactionNum(lInput)) return true;
1047  }
1048 
1049  return false;
1050 }
1051 
1053 {
1054  for (const auto& it : m_mapParties) {
1055  const OTParty* pParty = it.second;
1056  OT_ASSERT(nullptr != pParty);
1057 
1058  pParty->GetAllTransactionNumbers(numlistOutput);
1059  }
1060 }
1061 
1062 int64_t OTSmartContract::GetOpeningNumber(const OTIdentifier& theNymID) const
1063 {
1064  OTAgent* pAgent = nullptr;
1065  OTParty* pParty = FindPartyBasedOnNymIDAsAgent(theNymID, &pAgent);
1066 
1067  if (nullptr != pParty) {
1068  OT_ASSERT_MSG(nullptr != pAgent,
1069  "OT_ASSERT: nullptr != pAgent in "
1070  "OTSmartContract::GetOpeningNumber.\n");
1071  return pParty->GetOpeningTransNo();
1072  }
1073 
1074  return 0;
1075 }
1076 
1077 int64_t OTSmartContract::GetClosingNumber(const OTIdentifier& theAcctID) const
1078 {
1079  OTPartyAccount* pPartyAcct =
1080  GetPartyAccountByID(theAcctID); // from OTScriptable.
1081 
1082  if (nullptr != pPartyAcct) {
1083  return pPartyAcct->GetClosingTransNo();
1084  }
1085 
1086  return 0;
1087 }
1088 
1089 /*
1090  " 6 minutes == 360 seconds\n"
1091  "10 minutes == 600 seconds\n"
1092  " 1 hour == 3600 seconds\n"
1093  " 1 day == 86400 seconds\n"
1094  "30 days == 2592000 seconds\n"
1095  " 3 months == 7776000 seconds\n"
1096  " 6 months == 15552000 seconds\n\n"
1097  "12 months == 31104000 seconds\n\n"
1098  */
1099 
1100 // onProcess will trigger X seconds from now...
1101 //
1103  std::string str_seconds_from_now) // if this is <=0, then it sets next
1104  // process date to 0.
1105 {
1106  if (str_seconds_from_now.size() <= 0) // string length...
1107  {
1108  otOut << "OTSmartContract::" << __FUNCTION__
1109  << ": blank input (str_seconds_from_now).\n";
1110  }
1111  else {
1112  const int64_t tPlus = OTString::StringToLong(str_seconds_from_now);
1113 
1114  if (tPlus > 0)
1117  else
1118  SetNextProcessDate(OT_TIME_ZERO); // This way, you can deactivate
1119  // the timer, by setting the next
1120  // process date to 0.
1121  }
1122 }
1123 
1124 std::string OTSmartContract::GetRemainingTimer() const // returns seconds left
1125  // on the timer, in
1126  // string format, or "0".
1127 {
1128  const time64_t& tNextDate = GetNextProcessDate();
1129  const time64_t tCurrent = OTTimeGetCurrentTime();
1130 
1131  OTString strReturnVal("0"); // the default return value is "0".
1132 
1133  if (tNextDate > OT_TIME_ZERO) {
1134  const int64_t tSecondsLeft = OTTimeGetTimeInterval(tNextDate, tCurrent);
1135  strReturnVal.Format("%" PRId64 "", tSecondsLeft);
1136  }
1137 
1138  return strReturnVal.Get();
1139 }
1140 
1142 {
1143  // Not much needed here. Done, I guess.
1144 
1145  otErr << "FYI: OTSmartContract::onRemovalFromCron was just called. \n";
1146 
1147  // Trigger a script maybe.
1148  // OR maybe it's too late for scripts.
1149  // I give myself an onRemoval() here in C++, but perhaps I cut
1150  // off the SCRIPTS after onFinalReceipt(). I think that's best.
1151 }
1152 
1153 // Done.
1154 // called by HookActivationOnCron().
1155 //
1157 {
1158  OT_ASSERT(nullptr != GetCron());
1159 
1160  if (GetCron()->GetTransactionCount() < 1) {
1161  otOut << __FUNCTION__ << ": Failed to process smart contract "
1162  << GetTransactionNum() << ": Out of transaction numbers for "
1163  "receipts! Flagging for removal.\n";
1164  FlagForRemoval();
1165  return;
1166  }
1167 
1168  // Execute the scripts (clauses) that have registered for this hook.
1169 
1170  const std::string str_HookName(SMARTCONTRACT_HOOK_ON_ACTIVATE);
1171  mapOfClauses theMatchingClauses;
1172 
1173  if (GetHooks(str_HookName, theMatchingClauses)) {
1174  otOut << "Cron: Processing smart contract clauses for hook: "
1175  << SMARTCONTRACT_HOOK_ON_ACTIVATE << " \n";
1176 
1178  theMatchingClauses); // <============================================
1179  }
1180 }
1181 
1182 std::string OTSmartContract::GetAcctBalance(std::string from_acct_name)
1183 {
1184  OTCron* pCron = GetCron();
1185  OT_ASSERT(nullptr != pCron);
1186 
1187  OTPseudonym* pServerNym = pCron->GetServerNym();
1188  OT_ASSERT(nullptr != pServerNym);
1189 
1190  // Below this point, these are all good:
1191  //
1192  // pServerNym, pCron.
1193  //
1194 
1195  if (from_acct_name.size() <= 0) {
1196  otErr << "OTSmartContract::GetAcctBalance: error: from_acct_name is "
1197  "non-existent.\n";
1198  return 0;
1199  }
1200 
1201  // Below this point, these are all good:
1202  //
1203  // from_acct_name,
1204  // pServerNym, pCron.
1205 
1206  OTPartyAccount* pFromAcct = GetPartyAccount(from_acct_name);
1207 
1208  if (nullptr == pFromAcct) {
1209  otOut << "OTSmartContract::GetAcctBalances: error: from_acct ("
1210  << from_acct_name << ") not found on any party.\n";
1211  return 0;
1212  }
1213 
1214  // Below this point, these are all good:
1215  //
1216  // pFromAcct, from_acct_name,
1217  // pServerNym, pCron.
1218 
1219  OTAgent* pFromAgent =
1220  pFromAcct->GetAuthorizedAgent(); // This searches the account's party
1221  // for the account's authorized agent.
1222  // (That way it's impossible to get an agent for any other party.)
1223 
1224  if (nullptr == pFromAgent) {
1225  otOut << "OTSmartContract::GetAcctBalance: error: authorized agent ("
1226  << pFromAcct->GetAgentName() << ") not found for from_acct ("
1227  << from_acct_name << ") on acct's party.\n";
1228  return 0;
1229  }
1230 
1231  if (!pFromAgent->IsAnIndividual()) {
1232  otOut << "OTSmartContract::GetAcctBalance: error: authorized agent ("
1233  << pFromAcct->GetAgentName() << ") for from_acct ("
1234  << from_acct_name << ") is not an active agent.\n";
1235  return 0;
1236  }
1237  //
1238  // Below this point, these are all good:
1239  //
1240  // pFromAcct, from_acct_name, pFromAgent,
1241  // pServerNym, pCron.
1242 
1243  OTParty* pFromParty = pFromAgent->GetParty();
1244 
1245  if (nullptr == pFromParty) {
1246  otErr
1247  << "OTSmartContract::GetAcctBalance: error: Party pointer nullptr "
1248  "on authorized agent (" << pFromAcct->GetAgentName()
1249  << ") for from_acct (" << from_acct_name << ").\n";
1250  return 0;
1251  }
1252  //
1253  // Below this point, these are all good:
1254  //
1255  // pFromAcct, from_acct_name, pFromAgent, pFromParty,
1256  // pServerNym, pCron.
1257 
1258  // Done: I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY SINGLE
1259  // TIME THE SCRIPT
1260  // CALLS MOVE FUNDS. Maybe that's good, but since technically this only
1261  // needs to be verified before the
1262  // first call, and not for EVERY call during any of a script's runs, I
1263  // should probably move this verification
1264  // higher, such as each time the OTCronItem triggers, plus each time a party
1265  // triggers a clause directly
1266  // through the API (server message). As long as those are covered, I will be
1267  // able to remove it from here
1268  // which should be a significant improvement for performance.
1269  // It will be at the bottom of those same functions that
1270  // "ClearTemporaryPointers()" should finally be called.
1271  //
1272  //
1273  // FINAL DECISION: Redundant, already verified upon activation on cron.
1274  // See longer comment in OTSmartContract::StashAcctFunds()
1275  //
1276  // const OTString strServerID(GetServerID());
1277  //
1278  // mapOfNyms map_Nyms_Already_Loaded;
1279  // RetrieveNymPointers(map_Nyms_Already_Loaded);
1280  //
1281  //
1282  // if (!VerifyPartyAuthorization(*pFromParty, *pServerNym,
1283  // strServerID, &map_Nyms_Already_Loaded))
1284  // {
1285  // otErr << "OTSmartContract::GetAcctBalance: error: 'From' Party
1286  // (%s) not authorized for this contract.\n",
1287  // pFromParty->GetPartyName().c_str());
1288  // return 0;
1289  // }
1290 
1291  // A party might have many agents who are only voting groups, and cannot
1292  // actually sign for things
1293  // the way that nyms can. But at least ONE of those agents IS a Nym --
1294  // because there must have been
1295  // an authorizing agent who initially signed to accept the agreement, and
1296  // who fronted the opening
1297  // transaction number that activated it.
1298  //
1299  // Similarly, the authorized agent for any given party's account (each
1300  // account has its own authorized
1301  // agent) MUST be an active agent (an active agent is one with a
1302  // Nym--whether that Nym is representing
1303  // himself as the party, or whether representing some entity as an employee
1304  // in a role). Why MUST the
1305  // authorized agent be an active agent? Because when funds are moved, that
1306  // Nym must be loaded since
1307  // the account must show that Nym as a legal owner/agent. The MoveFunds will
1308  // cause a paymentReceipt to
1309  // drop into the Inbox for the relevant asset accounts, and that
1310  // paymentReceipt can ONLY be accepted
1311  // by that same Nym, who must use a transaction # that he signed for
1312  // previously and received through
1313  // his nymbox. There is actually no justification at all to take funds from
1314  // that account, since the
1315  // new balance has not yet been signed, UNLESS THE PAYMENTRECEIPT CONTAINS A
1316  // VALID, SIGNED AUTHORIZATION
1317  // FROM THE ACCOUNT HOLDER. *That* is why the authorizing agent must either
1318  // be the Party's Owner himself
1319  // (representing himself as an agent, which most will do) in which case he
1320  // will appear as the valid
1321  // owner of the account, OR he MUST be a Nym working in a Valid Role for an
1322  // Entity, where said Entity is
1323  // the valid owner on the account in question. Either OT, it will be
1324  // possible in OT for him to sign for
1325  // the paymentReceipts when they come in, and impossible for him to escape
1326  // liability for them.
1327  // (That's the idea anyway.)
1328  //
1329  // Since we know that the Authorized Agent for an account must be an ACTIVE
1330  // agent (one way or the other)
1331  // then we can error out here if he's not. We can then pass in his Nym ID.
1332  //
1333 
1334  OTIdentifier theFromAgentID;
1335  const bool bFromAgentID = pFromAgent->GetSignerID(theFromAgentID);
1336 
1337  if (!bFromAgentID) {
1338  otErr << "OTSmartContract::GetAcctBalance: Failed to find FromAgent's "
1339  "Signer ID: " << pFromAgent->GetName() << " \n";
1340  return 0;
1341  }
1342 
1343  if (!pFromAcct->GetAcctID().Exists()) {
1344  otErr << "OTSmartContract::GetAcctBalance: Error: FromAcct has empty "
1345  "AcctID: " << from_acct_name << " \n";
1346  return 0;
1347  }
1348 
1349  const OTIdentifier theFromAcctID(pFromAcct->GetAcctID());
1350  //
1351  // BELOW THIS POINT, theFromAcctID and theFromAgentID available.
1352 
1353  const OTIdentifier SERVER_ID(pCron->GetServerID());
1354  const OTIdentifier SERVER_USER_ID(*pServerNym);
1355 
1356  const std::string str_party_id = pFromParty->GetPartyID();
1357  const OTString strPartyID(str_party_id);
1358  const OTIdentifier PARTY_USER_ID(strPartyID);
1359 
1360  const OTIdentifier PARTY_ACCT_ID(pFromAcct->GetAcctID());
1361 
1362  // Load up the party's account so we can get the balance.
1363  //
1364  OTAccount* pPartyAssetAcct =
1365  OTAccount::LoadExistingAccount(PARTY_ACCT_ID, SERVER_ID);
1366 
1367  if (nullptr == pPartyAssetAcct) {
1368  otOut << "OTSmartContract::GetAcctBalance: ERROR verifying existence "
1369  "of source account.\n";
1370  FlagForRemoval(); // Remove it from future Cron processing, please.
1371  return 0;
1372  }
1373  else if (!pPartyAssetAcct->VerifySignature(*pServerNym)) {
1374  otOut << "OTSmartContract::GetAcctBalance: ERROR failed to verify the "
1375  "server's signature on the party's account.\n";
1376  FlagForRemoval(); // Remove it from future Cron processing, please.
1377  return 0;
1378  }
1379  else if (!pPartyAssetAcct->VerifyOwnerByID(PARTY_USER_ID)) {
1380  otOut << "OTSmartContract::GetAcctBalance: ERROR failed to verify "
1381  "party user ownership of party account.\n";
1382  FlagForRemoval(); // Remove it from future Cron processing, please.
1383  return 0;
1384  }
1385  // Past this point we know pPartyAssetAcct is good and will clean itself up.
1386  std::unique_ptr<OTAccount> theSourceAcctSmrtPtr(pPartyAssetAcct);
1387 
1388  OTString strBalance;
1389  strBalance.Format("%lld", pPartyAssetAcct->GetBalance());
1390 
1391  return strBalance.Get();
1392 }
1393 
1394 std::string OTSmartContract::GetAssetTypeIDofAcct(std::string from_acct_name)
1395 {
1396  OTCron* pCron = GetCron();
1397  OT_ASSERT(nullptr != pCron);
1398 
1399  OTPseudonym* pServerNym = pCron->GetServerNym();
1400  OT_ASSERT(nullptr != pServerNym);
1401 
1402  // Below this point, these are all good:
1403  //
1404  // pServerNym, pCron.
1405  //
1406 
1407  std::string str_return_value;
1408 
1409  if (from_acct_name.size() <= 0) {
1410  otErr << "OTSmartContract::GetAssetTypeIDofAcct: error: from_acct_name "
1411  "is non-existent.\n";
1412  return str_return_value;
1413  }
1414 
1415  // Below this point, these are all good:
1416  //
1417  // from_acct_name,
1418  // pServerNym, pCron.
1419 
1420  OTPartyAccount* pFromAcct = GetPartyAccount(from_acct_name);
1421 
1422  if (nullptr == pFromAcct) {
1423  otOut << "OTSmartContract::GetAssetTypeIDofAcct: error: from_acct ("
1424  << from_acct_name << ") not found on any party.\n";
1425  return str_return_value;
1426  }
1427 
1428  // Below this point, these are all good:
1429  //
1430  // pFromAcct, from_acct_name,
1431  // pServerNym, pCron.
1432 
1433  OTAgent* pFromAgent =
1434  pFromAcct->GetAuthorizedAgent(); // This searches the account's party
1435  // for the account's authorized agent.
1436  // (That way it's impossible to get an agent for any other party.)
1437 
1438  if (nullptr == pFromAgent) {
1439  otOut << "OTSmartContract::GetAssetTypeIDofAcct: error: authorized "
1440  "agent (" << pFromAcct->GetAgentName()
1441  << ") not found for from_acct (" << from_acct_name
1442  << ") on acct's party.\n";
1443  return str_return_value;
1444  }
1445 
1446  if (!pFromAgent->IsAnIndividual()) {
1447  otOut << "OTSmartContract::GetAssetTypeIDofAcct: error: authorized "
1448  "agent (" << pFromAcct->GetAgentName() << ") for from_acct ("
1449  << from_acct_name << ") is not an active agent.\n";
1450  return str_return_value;
1451  }
1452  //
1453  // Below this point, these are all good:
1454  //
1455  // pFromAcct, from_acct_name, pFromAgent,
1456  // pServerNym, pCron.
1457 
1458  OTParty* pFromParty = pFromAgent->GetParty();
1459 
1460  if (nullptr == pFromParty) {
1461  otErr << "OTSmartContract::GetAssetTypeIDofAcct: error: Party pointer "
1462  "nullptr on authorized agent (" << pFromAcct->GetAgentName()
1463  << ") for from_acct (" << from_acct_name << ").\n";
1464  return str_return_value;
1465  }
1466  //
1467  // Below this point, these are all good:
1468  //
1469  // pFromAcct, from_acct_name, pFromAgent, pFromParty,
1470  // pServerNym, pCron.
1471 
1472  // Done: I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY SINGLE
1473  // TIME THE SCRIPT
1474  // CALLS MOVE FUNDS. Maybe that's good, but since technically this only
1475  // needs to be verified before the
1476  // first call, and not for EVERY call during any of a script's runs, I
1477  // should probably move this verification
1478  // higher, such as each time the OTCronItem triggers, plus each time a party
1479  // triggers a clause directly
1480  // through the API (server message). As long as those are covered, I will be
1481  // able to remove it from here
1482  // which should be a significant improvement for performance.
1483  // It will be at the bottom of those same functions that
1484  // "ClearTemporaryPointers()" should finally be called.
1485  //
1486  //
1487  // FINAL DECISION: Redunant, already done upon activation onto cron.
1488  // Furthermore, expects no stashes to exist,
1489  // since they can only be created after activation. (Interfered with script
1490  // operations by complaining whenever
1491  // there was a stash.) See longer comment in StashAcctFunds().
1492  //
1493  // const OTString strServerID(GetServerID());
1494  //
1495  // mapOfNyms map_Nyms_Already_Loaded;
1496  // RetrieveNymPointers(map_Nyms_Already_Loaded);
1497  //
1498  //
1499  // if (!VerifyPartyAuthorization(*pFromParty, *pServerNym,
1500  // strServerID, &map_Nyms_Already_Loaded))
1501  // {
1502  // otErr << "OTSmartContract::GetAssetTypeIDofAcct: error: 'From'
1503  // Party (%s) not authorized for this contract.\n",
1504  // pFromParty->GetPartyName().c_str());
1505  // return str_return_value;
1506  // }
1507 
1508  // A party might have many agents who are only voting groups, and cannot
1509  // actually sign for things
1510  // the way that nyms can. But at least ONE of those agents IS a Nym --
1511  // because there must have been
1512  // an authorizing agent who initially signed to accept the agreement, and
1513  // who fronted the opening
1514  // transaction number that activated it.
1515  //
1516  // Similarly, the authorized agent for any given party's account (each
1517  // account has its own authorized
1518  // agent) MUST be an active agent (an active agent is one with a
1519  // Nym--whether that Nym is representing
1520  // himself as the party, or whether representing some entity as an employee
1521  // in a role). Why MUST the
1522  // authorized agent be an active agent? Because when funds are moved, that
1523  // Nym must be loaded since
1524  // the account must show that Nym as a legal owner/agent. The MoveFunds will
1525  // cause a paymentReceipt to
1526  // drop into the Inbox for the relevant asset accounts, and that
1527  // paymentReceipt can ONLY be accepted
1528  // by that same Nym, who must use a transaction # that he signed for
1529  // previously and received through
1530  // his nymbox. There is actually no justification at all to take funds from
1531  // that account, since the
1532  // new balance has not yet been signed, UNLESS THE PAYMENTRECEIPT CONTAINS A
1533  // VALID, SIGNED AUTHORIZATION
1534  // FROM THE ACCOUNT HOLDER. *That* is why the authorizing agent must either
1535  // be the Party's Owner himself
1536  // (representing himself as an agent, which most will do) in which case he
1537  // will appear as the valid
1538  // owner of the account, OR he MUST be a Nym working in a Valid Role for an
1539  // Entity, where said Entity is
1540  // the valid owner on the account in question. Either OT, it will be
1541  // possible in OT for him to sign for
1542  // the paymentReceipts when they come in, and impossible for him to escape
1543  // liability for them.
1544  // (That's the idea anyway.)
1545  //
1546  // Since we know that the Authorized Agent for an account must be an ACTIVE
1547  // agent (one way or the other)
1548  // then we can error out here if he's not. We can then pass in his Nym ID.
1549  //
1550 
1551  OTIdentifier theFromAgentID;
1552  const bool bFromAgentID = pFromAgent->GetSignerID(theFromAgentID);
1553 
1554  if (!bFromAgentID) {
1555  otErr << "OTSmartContract::GetAssetTypeIDofAcct: Failed to find "
1556  "FromAgent's Signer ID: " << pFromAgent->GetName() << " \n";
1557  return str_return_value;
1558  }
1559 
1560  if (!pFromAcct->GetAcctID().Exists()) {
1561  otErr << "OTSmartContract::GetAssetTypeIDofAcct: Error: FromAcct has "
1562  "empty AcctID: " << from_acct_name << " \n";
1563  return str_return_value;
1564  }
1565 
1566  const OTIdentifier theFromAcctID(pFromAcct->GetAcctID());
1567  //
1568  // BELOW THIS POINT, theFromAcctID and theFromAgentID available.
1569 
1570  const OTIdentifier SERVER_ID(pCron->GetServerID());
1571  const OTIdentifier SERVER_USER_ID(*pServerNym);
1572 
1573  const std::string str_party_id = pFromParty->GetPartyID();
1574  const OTString strPartyID(str_party_id);
1575  const OTIdentifier PARTY_USER_ID(strPartyID);
1576 
1577  const OTIdentifier PARTY_ACCT_ID(pFromAcct->GetAcctID());
1578 
1579  // Load up the party's account and get the asset type.
1580  //
1581  OTAccount* pPartyAssetAcct =
1582  OTAccount::LoadExistingAccount(PARTY_ACCT_ID, SERVER_ID);
1583 
1584  if (nullptr == pPartyAssetAcct) {
1585  otOut << "OTSmartContract::GetAssetTypeIDofAcct: ERROR verifying "
1586  "existence of source account.\n";
1587  FlagForRemoval(); // Remove it from future Cron processing, please.
1588  return str_return_value;
1589  }
1590  else if (!pPartyAssetAcct->VerifySignature(*pServerNym)) {
1591  otOut << "OTSmartContract::GetAssetTypeIDofAcct: ERROR failed to "
1592  "verify the server's signature on the party's account.\n";
1593  FlagForRemoval(); // Remove it from future Cron processing, please.
1594  return str_return_value;
1595  }
1596  else if (!pPartyAssetAcct->VerifyOwnerByID(PARTY_USER_ID)) {
1597  otOut << "OTSmartContract::GetAssetTypeIDofAcct: ERROR failed to "
1598  "verify party user ownership of party account.\n";
1599  FlagForRemoval(); // Remove it from future Cron processing, please.
1600  return str_return_value;
1601  }
1602  // Past this point we know pPartyAssetAcct is good and will clean itself up.
1603  std::unique_ptr<OTAccount> theSourceAcctSmrtPtr(pPartyAssetAcct);
1604 
1605  const OTString strAssetTypeID(pPartyAssetAcct->GetAssetTypeID());
1606  str_return_value = strAssetTypeID.Get();
1607 
1608  return str_return_value;
1609 }
1610 
1611 std::string OTSmartContract::GetStashBalance(std::string from_stash_name,
1612  std::string asset_type_id)
1613 {
1614  OTCron* pCron = GetCron();
1615  OT_ASSERT(nullptr != pCron);
1616 
1617  OTPseudonym* pServerNym = pCron->GetServerNym();
1618  OT_ASSERT(nullptr != pServerNym);
1619 
1620  // Below this point, these are all good:
1621  //
1622  // pServerNym, pCron.
1623  //
1624 
1625  if (from_stash_name.size() <= 0) {
1626  otErr << "OTSmartContract::GetStashBalance: error: from_stash_name is "
1627  "non-existent.\n";
1628  return 0;
1629  }
1630  if (asset_type_id.size() <= 0) {
1631  otErr << "OTSmartContract::GetStashBalance: error: asset_type_id is "
1632  "non-existent.\n";
1633  return 0;
1634  }
1635 
1636  // Below this point, these are all good:
1637  //
1638  // from_stash_name,
1639  // asset_type_id
1640  // pServerNym, pCron.
1641  //
1642 
1643  OTStash* pStash = GetStash(from_stash_name); // This ALWAYS succeeds.
1644  // (It will OT_ASSERT()
1645  // if failure.)
1646 
1647  //
1648  // Below this point, these are all good:
1649  //
1650  // pStash, from_stash_name,
1651  // asset_type_id
1652  // pServerNym, pCron.
1653  //
1654  OTString strBalance;
1655  strBalance.Format("%lld", pStash->GetAmount(asset_type_id));
1656  return strBalance.Get();
1657 }
1658 
1660 {
1661  OTCron* pCron = GetCron();
1662  OT_ASSERT(nullptr != pCron);
1663 
1664  OTPseudonym* pServerNym = pCron->GetServerNym();
1665  OT_ASSERT(nullptr != pServerNym);
1666 
1667  // Below this point, these are all good:
1668  //
1669  // pServerNym, pCron.
1670  //
1671 
1672  const int64_t lNewTransactionNumber = pCron->GetNextTransactionNumber();
1673  bool bDroppedNotice = false;
1674 
1675  // OT_ASSERT(lNewTransactionNumber > 0); // this can be my reminder.
1676  if (0 == lNewTransactionNumber) {
1677  otErr << __FUNCTION__ << ": ** ERROR: Notice not sent to parties, "
1678  "since no transaction numbers were "
1679  "available!\n";
1680  }
1681  else {
1683  SignContract(*pServerNym);
1684  SaveContract();
1685 
1686  const OTString strReference(*this);
1687  bDroppedNotice = SendNoticeToAllParties(
1688  true, // bSuccessMsg=true
1689  *pServerNym, GetServerID(), lNewTransactionNumber,
1690  // GetTransactionNum(), // each party has its own opening number.
1691  strReference); // pstrNote and pstrAttachment aren't used in this
1692  // case.
1693 
1694  otOut << __FUNCTION__
1695  << ": Dropping notifications into all parties' nymboxes: "
1696  << (bDroppedNotice ? "Success" : "Failure") << "\n";
1697  }
1698 
1699  return bDroppedNotice;
1700 }
1701 
1702 bool OTSmartContract::SendNoticeToParty(std::string party_name)
1703 {
1704  OTCron* pCron = GetCron();
1705  OT_ASSERT(nullptr != pCron);
1706 
1707  OTPseudonym* pServerNym = pCron->GetServerNym();
1708  OT_ASSERT(nullptr != pServerNym);
1709 
1710  // Below this point, these are all good:
1711  //
1712  // pServerNym, pCron.
1713 
1714  OTParty* pParty = GetParty(party_name);
1715 
1716  if (nullptr == pParty) {
1717  otOut << __FUNCTION__ << ": Unable to find this party: " << party_name
1718  << "\n";
1719  return false;
1720  }
1721  // Below this point, pParty is good.
1722 
1723  // ...This WILL check to see if pParty has its Opening number verified as
1724  // issued.
1725  // (If the opening number is > 0 then VerifyPartyAuthorization() is smart
1726  // enough to verify it.)
1727  //
1728  // To KNOW that a party has the right to even ASK the script to cancel a
1729  // contract, MEANS that
1730  // (1) The party is listed as a party on the contract. (2) The party's copy
1731  // of that contract
1732  // is signed by the authorizing agent for that party. and (3) The opening
1733  // transaction number for
1734  // that party is verified as issued for authorizing agent. (2 and 3 are both
1735  // performed at the same
1736  // time, in VerifyPartyAuthorization(), since the agent may need to be
1737  // loaded in order to verify
1738  // them.) 1 is already done by this point, as it's performed above.
1739  //
1740  // Done: notice this code appears in CanCancelContract() (this function) as
1741  // well as
1742  // OTScriptable::CanExecuteClause.
1743  // Therefore I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY
1744  // SINGLE TIME THE SCRIPT
1745  // CALLS ANY CLAUSE OR OT NATIVE FUNCTION. Since technically this only
1746  // needs to be verified before the
1747  // first call, and not for EVERY call during any of a script's runs, I
1748  // should probably move this verification
1749  // higher, such as each time the OTCronItem triggers, plus each time a party
1750  // triggers a clause directly
1751  // through the API (server message). As long as those are covered, I will be
1752  // able to remove it from here
1753  // which should be a significant improvement for performance.
1754  // It will be at the bottom of those same functions that
1755  // "ClearTemporaryPointers()" should finally be called.
1756  //
1757  // Also todo: Need to implement MOVE CONSTRUCTORS and MOVE COPY
1758  // CONSTRUCTORS all over the place,
1759  // once I'm sure C++0x build environments are available for all of the
1760  // various OT platforms. That should
1761  // be another great performance boost!
1762  //
1763  // FINAL DECISION: See longer comment in
1764  // OTSmartContract::StashAcctFunds(). This is redundant and was
1765  // removed. It expects itself to be executed only upon the initial
1766  // activation of a smart contract, and
1767  // not again after. (For example, it disallows stashes, which cannot exist
1768  // prior to activation.)
1769  //
1770  bool bDroppedNotice = false;
1771  const int64_t lNewTransactionNumber = pCron->GetNextTransactionNumber();
1772 
1773  // OT_ASSERT(lNewTransactionNumber > 0); // this can be my reminder.
1774  if (0 == lNewTransactionNumber) {
1775  otErr << __FUNCTION__ << ": ** ERROR: Notice not sent to party, since "
1776  "no transaction numbers were available!\n";
1777  }
1778  else {
1780  SignContract(*pServerNym);
1781  SaveContract();
1782 
1783  const OTString strReference(*this);
1784 
1785  bDroppedNotice = pParty->SendNoticeToParty(
1786  true, // bSuccessMsg=true. True in general means "success" and false
1787  // means "failure."
1788  *pServerNym, GetServerID(), lNewTransactionNumber,
1789  // GetTransactionNum(), // each party has its own opening trans #
1790  // and supplies it internally.
1791  strReference);
1792 
1793  otOut << __FUNCTION__ << ": "
1794  << (bDroppedNotice ? "Success" : "Failure")
1795  << " dropping notification into party's nymbox: "
1796  << pParty->GetPartyName() << "\n";
1797  }
1798 
1799  return bDroppedNotice;
1800 }
1801 
1802 // Higher-level. Can be called from inside scripts.
1803 //
1804 // Returns success if funds were moved.
1805 // This function does not run any scripts, but it CAN be executed from within
1806 // the scripts.
1807 // Any movement of funds to-or-from any account will automatically try to
1808 // load/use the
1809 // appropriate authorizing agent for that account (or use him, if he's already
1810 // loaded on
1811 // this smart contract.)
1812 //
1813 // DONE: audit security. Whenever I add any funds to a stash, there should be an
1814 // internal
1815 // server account where the backing funds are stored, the same as with cash.
1816 // This is so that
1817 // stashed funds will show up properly on an audit.
1818 //
1819 bool OTSmartContract::StashAcctFunds(std::string from_acct_name,
1820  std::string to_stash_name,
1821  std::string str_Amount)
1822 {
1823  OTCron* pCron = GetCron();
1824  OT_ASSERT(nullptr != pCron);
1825 
1826  OTPseudonym* pServerNym = pCron->GetServerNym();
1827  OT_ASSERT(nullptr != pServerNym);
1828 
1829  // Below this point, these are all good:
1830  //
1831  // pServerNym, pCron.
1832 
1833  if (str_Amount.size() < 1) {
1834  otOut << "OTSmartContract::StashAcctFunds: Error: empty amount.\n";
1835  return false;
1836  }
1837 
1838  const int64_t lAmount = atol(str_Amount.c_str());
1839 
1840  if (lAmount <= 0) {
1841  otOut << "OTSmartContract::StashAcctFunds: Error: lAmount cannot be 0 "
1842  "or <0. (Value passed in was " << lAmount << ".)\n";
1843  return false;
1844  }
1845 
1846  if (from_acct_name.size() <= 0) {
1847  otErr << "OTSmartContract::StashAcctFunds: error: from_acct_name is "
1848  "non-existent.\n";
1849  return false;
1850  }
1851  if (to_stash_name.size() <= 0) {
1852  otErr << "OTSmartContract::StashAcctFunds: error: to_stash_name is "
1853  "non-existent.\n";
1854  return false;
1855  }
1856 
1857  // Below this point, these are all good:
1858  //
1859  // from_acct_name,
1860  // to_stash_name,
1861  // pServerNym, pCron.
1862  //
1863 
1864  OTPartyAccount* pFromAcct = GetPartyAccount(from_acct_name);
1865  OTStash* pStash = GetStash(to_stash_name); // This ALWAYS succeeds.
1866  // (It will OT_ASSERT() if
1867  // failure.)
1868 
1869  if (nullptr == pFromAcct) {
1870  otOut << "OTSmartContract::StashAcctFunds: error: from_acct ("
1871  << from_acct_name << ") not found on any party.\n";
1872  return false;
1873  }
1874 
1875  // Below this point, these are all good:
1876  //
1877  // pFromAcct, from_acct_name,
1878  // pStash, to_stash_name,
1879  // pServerNym, pCron.
1880  //
1881 
1882  OTAgent* pFromAgent =
1883  pFromAcct->GetAuthorizedAgent(); // This searches the account's party
1884  // for the account's authorized agent.
1885  // (That way it's impossible to get an agent for any other party.)
1886 
1887  if (nullptr == pFromAgent) {
1888  otOut << "OTSmartContract::StashAcctFunds: error: authorized agent ("
1889  << pFromAcct->GetAgentName() << ") not found for from_acct ("
1890  << from_acct_name << ") on acct's party.\n";
1891  return false;
1892  }
1893 
1894  if (!pFromAgent->IsAnIndividual()) {
1895  otOut << "OTSmartContract::StashAcctFunds: error: authorized agent ("
1896  << pFromAcct->GetAgentName() << ") for from_acct ("
1897  << from_acct_name << ") is not an active agent.\n";
1898  return false;
1899  }
1900  //
1901  // Below this point, these are all good:
1902  //
1903  // pFromAcct, from_acct_name, pFromAgent,
1904  // pStash, to_stash_name,
1905  // pServerNym, pCron.
1906 
1907  OTParty* pFromParty = pFromAgent->GetParty();
1908 
1909  if (nullptr == pFromParty) {
1910  otErr
1911  << "OTSmartContract::StashAcctFunds: error: Party pointer nullptr "
1912  "on authorized agent (" << pFromAcct->GetAgentName()
1913  << ") for from_acct (" << from_acct_name << ").\n";
1914  return false;
1915  }
1916  //
1917  // Below this point, these are all good:
1918  //
1919  // pFromAcct, from_acct_name, pFromAgent, pFromParty,
1920  // pStash, to_stash_name,
1921  // pServerNym, pCron.
1922 
1923  // DONE: Problem: I can see that THIS VERIFICATION CODE WILL GET CALLED
1924  // EVERY SINGLE TIME THE SCRIPT
1925  // CALLS MOVE FUNDS. Maybe that's good, but since technically this only
1926  // needs to be verified before the
1927  // first call, and not for EVERY call during any of a script's runs, I
1928  // should probably move this verification
1929  // higher, such as each time the OTCronItem triggers, plus each time a party
1930  // triggers a clause directly
1931  // through the API (server message). As long as those are covered, I will be
1932  // able to remove it from here
1933  // which should be a significant improvement for performance.
1934  // It will be at the bottom of those same functions that
1935  // "ClearTemporaryPointers()" should finally be called.
1936  //
1937  //
1938  // const OTString strServerID(GetServerID());
1939 
1940  // mapOfNyms map_Nyms_Already_Loaded;
1941  // RetrieveNymPointers(map_Nyms_Already_Loaded);
1942 
1943  // FINAL DECISION: Since this verification is already done for the smart
1944  // contract to have been activated onto
1945  // cron in the first place, it is redundant to have it here.
1946  // Furthermore, what if a single clause calls stash_funds 30 times in a
1947  // loop? Does that mean we need to verify
1948  // all the parties and accounts 30 times, every single time we call that
1949  // clause? CLearly such is redundant, and
1950  // would be targeted in any optimization effort.
1951  // Furthermore, since actually running the software, it's become apparent
1952  // that it is no longer even appropriate
1953  // to Verify anymore, since stashes can exist after a smartcontract has been
1954  // activated, while this function
1955  // specifically verifies that no stashes exist, since it presumes that it is
1956  // only called during the initial
1957  // activation of the cron item, when no stashes SHOULD exist (since they are
1958  // only created after activation, by
1959  // the server itself, at the behest of the scripts.)
1960 
1961  // A party might have many agents who are only voting groups, and cannot
1962  // actually sign for things
1963  // the way that nyms can. But at least ONE of those agents IS a Nym --
1964  // because there must have been
1965  // an authorizing agent who initially signed to accept the agreement, and
1966  // who fronted the opening
1967  // transaction number that activated it.
1968  //
1969  // Similarly, the authorized agent for any given party's account (each
1970  // account has its own authorized
1971  // agent) MUST be an active agent (an active agent is one with a
1972  // Nym--whether that Nym is representing
1973  // himself as the party, or whether representing some entity as an employee
1974  // in a role). Why MUST the
1975  // authorized agent be an active agent? Because when funds are moved, that
1976  // Nym must be loaded since
1977  // the account must show that Nym as a legal owner/agent. The MoveFunds will
1978  // cause a paymentReceipt to
1979  // drop into the Inbox for the relevant asset accounts, and that
1980  // paymentReceipt can ONLY be accepted
1981  // by that same Nym, who must use a transaction # that he signed for
1982  // previously and received through
1983  // his nymbox. There is actually no justification at all to take funds from
1984  // that account, since the
1985  // new balance has not yet been signed, UNLESS THE PAYMENTRECEIPT CONTAINS A
1986  // VALID, SIGNED AUTHORIZATION
1987  // FROM THE ACCOUNT HOLDER. *That* is why the authorizing agent must either
1988  // be the Party's Owner himself
1989  // (representing himself as an agent, which most will do) in which case he
1990  // will appear as the valid
1991  // owner of the account, OR he MUST be a Nym working in a Valid Role for an
1992  // Entity, where said Entity is
1993  // the valid owner on the account in question. Either OT, it will be
1994  // possible in OT for him to sign for
1995  // the paymentReceipts when they come in, and impossible for him to escape
1996  // liability for them.
1997  // (That's the idea anyway.)
1998  //
1999  // Since we know that the Authorized Agent for an account must be an ACTIVE
2000  // agent (one way or the other)
2001  // then we can error out here if he's not. We can then pass in his Nym ID.
2002  //
2003 
2004  OTIdentifier theFromAgentID;
2005  const bool bFromAgentID = pFromAgent->GetSignerID(theFromAgentID);
2006 
2007  if (!bFromAgentID) {
2008  otErr << "OTSmartContract::StashAcctFunds: Failed to find FromAgent's "
2009  "Signer ID: " << pFromAgent->GetName() << " \n";
2010  return false;
2011  }
2012 
2013  if (!pFromAcct->GetAcctID().Exists()) {
2014  otErr << "OTSmartContract::StashAcctFunds: Error: FromAcct has empty "
2015  "AcctID: " << from_acct_name << " \n";
2016  return false;
2017  }
2018 
2019  const OTIdentifier theFromAcctID(pFromAcct->GetAcctID());
2020  //
2021  // BELOW THIS POINT, theFromAcctID and theFromAgentID available.
2022 
2023  // WE SET THESE HERE SO THE RECEIPT SHOWS, SUCCESS OR FAIL,
2024  // WHO THE INTENDED SENDER / RECIPIENT ARE FOR THAT RECEIPT.
2025  //
2027 
2028  theFromAgentID.GetString(m_strLastSenderUser); // This is the last User ID
2029  // of a party who SENT money.
2030  theFromAcctID.GetString(m_strLastSenderAcct); // This is the last Acct ID of
2031  // a party who SENT money.
2032  // theToAgentID.GetString(m_strLastRecipientUser); // This is the last
2033  // User ID of a party who RECEIVED money.
2034  // theToAcctID.GetString(m_strLastRecipientAcct); // This is the last
2035  // Acct ID of a party who RECEIVED money.
2036  // Above: the ToAgent and ToAcct are commented out,
2037  // since the funds are going into a stash.
2038 
2039  mapOfNyms map_Nyms_Already_Loaded;
2040  RetrieveNymPointers(map_Nyms_Already_Loaded);
2041 
2042  bool bMoved = StashFunds(map_Nyms_Already_Loaded, lAmount, theFromAcctID,
2043  theFromAgentID, *pStash);
2044  if (!bMoved) {
2045  otOut << "OTSmartContract::StashAcctFunds: Failed in final call. "
2046  "Values: from_acct: " << from_acct_name
2047  << ", to_stash: " << to_stash_name << ", lAmount: " << lAmount
2048  << ". \n";
2049  return false;
2050  }
2051 
2052  return true;
2053 }
2054 
2055 // Higher-level. Can be called from inside scripts.
2056 //
2057 // Returns success if funds were moved.
2058 // This function does not run any scripts, but it CAN be executed from within
2059 // the scripts.
2060 // Any movement of funds to-or-from any account will automatically try to
2061 // load/use the
2062 // appropriate authorizing agent for that account (or use him, if he's already
2063 // loaded on
2064 // this smart contract.)
2065 //
2066 // DONE: audit security. Whenever I add any funds to a stash, there should be an
2067 // internal
2068 // server account where the backing funds are stored, the same as with cash.
2069 // This is so that
2070 // stashed funds will show up properly on an audit.
2071 //
2072 bool OTSmartContract::UnstashAcctFunds(std::string to_acct_name,
2073  std::string from_stash_name,
2074  std::string str_Amount)
2075 {
2076  OTCron* pCron = GetCron();
2077  OT_ASSERT(nullptr != pCron);
2078 
2079  OTPseudonym* pServerNym = pCron->GetServerNym();
2080  OT_ASSERT(nullptr != pServerNym);
2081 
2082  // Below this point, these are all good:
2083  //
2084  // pServerNym, pCron.
2085  //
2086 
2087  if (str_Amount.size() < 1) {
2088  otOut << "OTSmartContract::UnstashAcctFunds: Error: empty amount.\n";
2089  return false;
2090  }
2091 
2092  const int64_t lAmount = atol(str_Amount.c_str());
2093 
2094  if (lAmount <= 0) {
2095  otOut << "OTSmartContract::UnstashAcctFunds: Error: lAmount cannot be "
2096  "0 or <0. (Value passed in was " << lAmount << ".)\n";
2097  return false;
2098  }
2099 
2100  if (to_acct_name.size() <= 0) {
2101  otErr << "OTSmartContract::UnstashAcctFunds: error: to_acct_name is "
2102  "non-existent.\n";
2103  return false;
2104  }
2105  if (from_stash_name.size() <= 0) {
2106  otErr << "OTSmartContract::UnstashAcctFunds: error: from_stash_name is "
2107  "non-existent.\n";
2108  return false;
2109  }
2110 
2111  // Below this point, these are all good:
2112  //
2113  // to_acct_name,
2114  // from_stash_name,
2115  // pServerNym, pCron.
2116 
2117  OTPartyAccount* pToAcct = GetPartyAccount(to_acct_name);
2118  OTStash* pStash = GetStash(from_stash_name); // This ALWAYS succeeds.
2119  // (It will OT_ASSERT()
2120  // if failure.)
2121 
2122  if (nullptr == pToAcct) {
2123  otOut << "OTSmartContract::UnstashAcctFunds: error: to_acct ("
2124  << to_acct_name << ") not found on any party.\n";
2125  return false;
2126  }
2127 
2128  // Below this point, these are all good:
2129  //
2130  // pToAcct, to_acct_name,
2131  // pStash, from_stash_name,
2132  // pServerNym, pCron.
2133 
2134  OTAgent* pToAgent =
2135  pToAcct->GetAuthorizedAgent(); // This searches the account's party for
2136  // the account's authorized agent.
2137  // (That way it's impossible to get an agent for any other party.)
2138 
2139  if (nullptr == pToAgent) {
2140  otOut << "OTSmartContract::UnstashAcctFunds: error: authorized agent ("
2141  << pToAcct->GetAgentName().Get() << ") not found for to_acct ("
2142  << to_acct_name << ") on acct's party.\n";
2143  return false;
2144  }
2145 
2146  if (!pToAgent->IsAnIndividual()) {
2147  otOut << "OTSmartContract::UnstashAcctFunds: error: authorized agent ("
2148  << pToAcct->GetAgentName().Get() << ") for to_acct ("
2149  << to_acct_name << ") is not an active agent.\n";
2150  return false;
2151  }
2152  //
2153  // Below this point, these are all good:
2154  //
2155  // pToAcct, to_acct_name, pToAgent,
2156  // pStash, from_stash_name,
2157  // pServerNym, pCron.
2158 
2159  OTParty* pToParty = pToAgent->GetParty();
2160 
2161  if (nullptr == pToParty) {
2162  otErr << "OTSmartContract::UnstashAcctFunds: error: Party pointer "
2163  "nullptr "
2164  "on authorized agent (" << pToAcct->GetAgentName()
2165  << ") for to_acct (" << to_acct_name << ").\n";
2166  return false;
2167  }
2168  //
2169  // Below this point, these are all good:
2170  //
2171  // pToAcct, to_acct_name, pToAgent, pToParty,
2172  // pStash, from_stash_name,
2173  // pServerNym, pCron.
2174 
2175  // Done: I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY SINGLE
2176  // TIME THE SCRIPT
2177  // CALLS MOVE FUNDS. Maybe that's good, but since technically this only
2178  // needs to be verified before the
2179  // first call, and not for EVERY call during any of a script's runs, I
2180  // should probably move this verification
2181  // higher, such as each time the OTCronItem triggers, plus each time a party
2182  // triggers a clause directly
2183  // through the API (server message). As long as those are covered, I will be
2184  // able to remove it from here
2185  // which should be a significant improvement for performance.
2186  // It will be at the bottom of those same functions that
2187  // "ClearTemporaryPointers()" should finally be called.
2188  //
2189  // FINAL DECISION: Redundant, removed. See comments in StashAcctFunds().
2190  //
2191  // A party might have many agents who are only voting groups, and cannot
2192  // actually sign for things
2193  // the way that nyms can. But at least ONE of those agents IS a Nym --
2194  // because there must have been
2195  // an authorizing agent who initially signed to accept the agreement, and
2196  // who fronted the opening
2197  // transaction number that activated it.
2198  //
2199  // Similarly, the authorized agent for any given party's account (each
2200  // account has its own authorized
2201  // agent) MUST be an active agent (an active agent is one with a
2202  // Nym--whether that Nym is representing
2203  // himself as the party, or whether representing some entity as an employee
2204  // in a role). Why MUST the
2205  // authorized agent be an active agent? Because when funds are moved, that
2206  // Nym must be loaded since
2207  // the account must show that Nym as a legal owner/agent. The MoveFunds will
2208  // cause a paymentReceipt to
2209  // drop into the Inbox for the relevant asset accounts, and that
2210  // paymentReceipt can ONLY be accepted
2211  // by that same Nym, who must use a transaction # that he signed for
2212  // previously and received through
2213  // his nymbox. There is actually no justification at all to take funds from
2214  // that account, since the
2215  // new balance has not yet been signed, UNLESS THE PAYMENTRECEIPT CONTAINS A
2216  // VALID, SIGNED AUTHORIZATION
2217  // FROM THE ACCOUNT HOLDER. *That* is why the authorizing agent must either
2218  // be the Party's Owner himself
2219  // (representing himself as an agent, which most will do) in which case he
2220  // will appear as the valid
2221  // owner of the account, OR he MUST be a Nym working in a Valid Role for an
2222  // Entity, where said Entity is
2223  // the valid owner on the account in question. Either OT, it will be
2224  // possible in OT for him to sign for
2225  // the paymentReceipts when they come in, and impossible for him to escape
2226  // liability for them.
2227  // (That's the idea anyway.)
2228  //
2229  // Since we know that the Authorized Agent for an account must be an ACTIVE
2230  // agent (one way or the other)
2231  // then we can error out here if he's not. We can then pass in his Nym ID.
2232  //
2233 
2234  OTIdentifier theToAgentID;
2235  const bool bToAgentID = pToAgent->GetSignerID(theToAgentID);
2236 
2237  if (!bToAgentID) {
2238  otErr << "OTSmartContract::UnstashAcctFunds: Failed to find 'To' "
2239  "Agent's Signer ID: " << pToAgent->GetName() << " \n";
2240  return false;
2241  }
2242 
2243  if (!pToAcct->GetAcctID().Exists()) {
2244  otErr << "OTSmartContract::UnstashAcctFunds: Error: ToAcct has empty "
2245  "AcctID: " << to_acct_name << " \n";
2246  return false;
2247  }
2248 
2249  const OTIdentifier theToAcctID(pToAcct->GetAcctID());
2250  //
2251  // BELOW THIS POINT, theToAcctID and theToAgentID available.
2252 
2253  // WE SET THESE HERE SO THE RECEIPT SHOWS, SUCCESS OR FAIL,
2254  // WHO THE INTENDED SENDER / RECIPIENT ARE FOR THAT RECEIPT.
2255  //
2257 
2258  theToAgentID.GetString(m_strLastRecipientUser); // This is the last User ID
2259  // of a party who RECEIVED
2260  // money.
2261  theToAcctID.GetString(m_strLastRecipientAcct); // This is the last Acct ID
2262  // of a party who RECEIVED
2263  // money.
2264  // Above: the FromAgent and FromAcct are commented out,
2265  // since the funds are coming from a stash.
2266 
2267  const int64_t lNegativeAmount = (lAmount * (-1));
2268 
2269  mapOfNyms map_Nyms_Already_Loaded;
2270  RetrieveNymPointers(map_Nyms_Already_Loaded);
2271 
2272  bool bMoved = StashFunds(map_Nyms_Already_Loaded, lNegativeAmount,
2273  theToAcctID, theToAgentID, *pStash);
2274  if (!bMoved) {
2275  otOut << "OTSmartContract::UnstashAcctFunds: Failed in final call. "
2276  "Values: to_acct: " << to_acct_name
2277  << ", from_stash: " << from_stash_name << ", lAmount: " << lAmount
2278  << ". \n";
2279  return false;
2280  }
2281 
2282  return true;
2283 }
2284 
2285 // OTSmartContract::StashFunds is lower-level; it's used inside StashAcctFunds()
2286 // and UnstashAcctFunds(). (Similarly to how OTCronItem::MoveFunds() is used in-
2287 // side OTSmartContract::MoveAcctFunds().
2288 //
2289 // true == success, false == failure.
2290 //
2291 bool OTSmartContract::StashFunds(const mapOfNyms& map_NymsAlreadyLoaded,
2292  const int64_t& lAmount, // negative amount here
2293  // means UNstash.
2294  // Positive means
2295  // STASH.
2296  const OTIdentifier& PARTY_ACCT_ID,
2297  const OTIdentifier& PARTY_USER_ID,
2298  OTStash& theStash)
2299 {
2300  OTCron* pCron = GetCron();
2301  OT_ASSERT(nullptr != pCron);
2302 
2303  OTPseudonym* pServerNym = pCron->GetServerNym();
2304  OT_ASSERT(nullptr != pServerNym);
2305 
2306  if (0 == lAmount) {
2307  otOut << "OTSmartContract::StashFunds: a zero amount is not allowed.\n";
2308  return false;
2309  }
2310 
2311  const OTIdentifier SERVER_ID(pCron->GetServerID());
2312  const OTIdentifier SERVER_USER_ID(*pServerNym);
2313 
2314  // Load up the party's account and get the asset type, so we know which
2315  // stash to get off the stash.
2316  //
2317  OTAccount* pPartyAssetAcct =
2318  OTAccount::LoadExistingAccount(PARTY_ACCT_ID, SERVER_ID);
2319 
2320  if (nullptr == pPartyAssetAcct) {
2321  otOut << "OTSmartContract::StashFunds: ERROR verifying existence of "
2322  "source account.\n";
2323  FlagForRemoval(); // Remove it from future Cron processing, please.
2324  return false;
2325  }
2326  else if (!pPartyAssetAcct->VerifySignature(*pServerNym)) {
2327  otOut << "OTSmartContract::StashFunds: ERROR failed to verify the "
2328  "server's signature on the party's account.\n";
2329  FlagForRemoval(); // Remove it from future Cron processing, please.
2330  return false;
2331  }
2332  else if (!pPartyAssetAcct->VerifyOwnerByID(PARTY_USER_ID)) {
2333  otOut << "OTSmartContract::StashFunds: ERROR failed to verify party "
2334  "user ownership of party account.\n";
2335  FlagForRemoval(); // Remove it from future Cron processing, please.
2336  return false;
2337  }
2338  // Past this point we know pPartyAssetAcct is good and will clean itself up.
2339  std::unique_ptr<OTAccount> theSourceAcctSmrtPtr(pPartyAssetAcct);
2340 
2341  //
2342  // There could be many stashes, each with a name. (One was passed in
2343  // here...)
2344  // And inside each one is a stash for each asset type. So let's get the one
2345  // for the asset type matching the party's account.
2346  //
2347  const OTString strAssetTypeID(pPartyAssetAcct->GetAssetTypeID());
2348  const std::string str_asset_type_id = strAssetTypeID.Get();
2349 
2350  OTStashItem* pStashItem = theStash.GetStash(str_asset_type_id);
2351  OT_ASSERT(nullptr !=
2352  pStashItem); // should never happen. Creates if non-existent.
2353 
2354  // Below this point, pStashItem is good, and has the right asset_type_id.
2355 
2356  //
2357  const bool bUnstashing =
2358  (lAmount < 0); // If the amount is negative, then we're UNSTASHING.
2359  const int64_t lAbsoluteAmount =
2360  bUnstashing
2361  ? (lAmount * (-1))
2362  : lAmount; // NEGATIVE AMOUNT SHOULD BEHAVE AS "UNSTASH FUNDS" !!
2363 
2364  // Normally if you stash 10 clams, then your account is -10 clams, and your
2365  // stash is +10 clams.
2366  // Therefore if you unstash 5 gg, then your gg acct is +5 grams and your
2367  // stash is -5 grams.
2368  //
2369  // Thus if lAmount is > 0, as normal, that amount should be DEBITED from the
2370  // Party Acct, and CREDITED to the Stash Acct.
2371  // Whereas if lAmount were < 0, then that amount should be DEBITED from the
2372  // Stash Acct, and CREDITED to the Party Acct.
2373 
2374  // Below this point, lAbsoluteAmount is always a positive number.
2375  // Whereas if lAmount < 0, that means we are doing an UNSTASH in this
2376  // function.
2377  //
2378 
2379  // Whether the funds are coming from the party's acct, or from the stash,
2380  // WHEREVER they
2381  // are coming from, is that source LARGE enough to accommodate the amount
2382  // we're trying to move?
2383  //
2384 
2385  const int64_t lPartyAssetBalance = pPartyAssetAcct->GetBalance();
2386  const int64_t lStashItemAmount = pStashItem->GetAmount();
2387 
2388  const int64_t lSourceAmount =
2389  bUnstashing ? lStashItemAmount : lPartyAssetBalance;
2390 
2391  // If the source, minus amount, is less than 0, then it CANNOT accommodate
2392  // the action.
2393  //
2394  if ((lSourceAmount - lAbsoluteAmount) < 0) {
2395  otOut << "OTSmartContract::StashFunds: Not enough funds available in "
2396  "the source to accommodate this action.\n";
2397  return false;
2398  }
2399 
2400  bool bWasAcctCreated = false; // GetOrCreateAccount() will verifyContractID
2401  // and verifySignature on the account
2402  // internally.
2403  std::shared_ptr<OTAccount> pStashAccount = m_StashAccts.GetOrCreateAccount(
2404  *pServerNym, SERVER_USER_ID, pPartyAssetAcct->GetAssetTypeID(),
2405  SERVER_ID, bWasAcctCreated, GetTransactionNum());
2406 
2407  if (!pStashAccount) {
2408  OT_FAIL_MSG("ASSERT in OTSmartContract::StashFunds: returned nullptr "
2409  "pointer (should never happen.)\n");
2410  }
2411 
2412  if (bWasAcctCreated) {
2413  OTString strAcctID;
2414  pStashAccount->GetIdentifier(strAcctID);
2415 
2416  otOut << "OTSmartContract::StashFunds: Successfully created stash "
2417  "account ID: " << strAcctID
2418  << "\n (Stash acct has Asset Type ID: " << strAssetTypeID
2419  << ") \n";
2420 
2421  // Todo: Some kind of save here?
2422  // It's kind of unnecessary, since I've already verified that there's
2423  // enough funds at the source
2424  // to successfully do the transfer, AND I will already save at the end
2425  // of this call, since funds are
2426  // being moved.
2427  }
2428 
2429  if (!pStashAccount) {
2430  OT_FAIL_MSG("ASSERT in OTSmartContract::StashFunds: returned nullptr "
2431  "pointer (should never happen.)\n");
2432  }
2433 
2434  // This code is similar to above, but it checks the stash ACCT itself
2435  // instead of the stash entry.
2436  //
2437  // Whether the funds are coming from the party's acct, or from the stash
2438  // acct, WHEREVER they
2439  // are coming from, is that source LARGE enough to accommodate the amount
2440  // we're trying to move?
2441  //
2442  const int64_t lSourceAmount2 = bUnstashing ? pStashAccount->GetBalance()
2443  : pPartyAssetAcct->GetBalance();
2444 
2445  // If the source, minus amount, is less than 0, then it CANNOT accommodate
2446  // the action.
2447  //
2448  if ((lSourceAmount2 - lAbsoluteAmount) < 0) {
2449  otOut << "OTSmartContract::StashFunds: Not enough funds available in "
2450  "the stash acct to accommodate this action.\n";
2451  return false; // THIS SHOULD NEVER HAPPEN, SINCE WE ALREADY VERIFIED THE
2452  // AMOUNT BEFORE LOADING THE ACCOUNT. FYI.
2453  }
2454 
2455  // Make sure they're not the same Account IDs ...
2456  // Otherwise we would have to take care not to load them twice, like with
2457  // the Nyms below.
2458  // (Instead I just disallow it entirely. After all, even if I DID allow the
2459  // account to transfer
2460  // to itself, there would be no difference in balance than disallowing it.)
2461  //
2462  const OTIdentifier STASH_ACCT_ID(pStashAccount->GetRealAccountID());
2463 
2464  if (PARTY_ACCT_ID == STASH_ACCT_ID) {
2465  otErr << "OTSmartContract::StashFunds: ERROR: both account IDs were "
2466  "identical.\n";
2467  FlagForRemoval(); // Remove from Cron
2468  return false; // TODO: should have a "Validate Scripts" function that
2469  // weeds this crap out before we even get here. (There are
2470  // other examples...)
2471  }
2472 
2473  // SHOULD NEVER HAPPEN
2474  if (pPartyAssetAcct->GetAssetTypeID() != pStashAccount->GetAssetTypeID()) {
2475  otErr << "OTSmartContract::StashFunds: Aborted stash: Asset type ID "
2476  "doesn't match. THIS SHOULD NEVER HAPPEN.\n";
2477  FlagForRemoval(); // Remove from Cron
2478  return false;
2479  }
2480 
2481  if (!pStashAccount->VerifyOwnerByID(SERVER_USER_ID)) {
2482  otErr << "OTSmartContract::StashFunds: Error: Somehow the stash "
2483  "account isn't server-nym owned.\n";
2484  FlagForRemoval(); // Remove from Cron
2485  return false;
2486  }
2487  const OTIdentifier STASH_USER_ID(pStashAccount->GetUserID());
2488 
2489  bool bSuccess = false; // The return value.
2490 
2491  OTString strPartyUserID(PARTY_USER_ID), strStashUserID(STASH_USER_ID),
2492  strPartyAcctID(PARTY_ACCT_ID), strStashAcctID(STASH_ACCT_ID),
2493  strServerNymID(SERVER_USER_ID);
2494 
2495  // Need to load up the ORIGINAL VERSION OF THIS SMART CONTRACT
2496  // Will need to verify the party's signature, as well as attach a copy of it
2497  // to the receipt.
2498 
2499  // OTCronItem::LoadCronReceipt loads the original version with the user's
2500  // signature.
2501  // (Updated versions, as processing occurs, are signed by the server.)
2502  std::unique_ptr<OTCronItem> pOrigCronItem(
2504 
2505  OT_ASSERT(nullptr != pOrigCronItem); // How am I processing it now if the
2506  // receipt wasn't saved in the first
2507  // place??
2508  // TODO: Decide global policy for handling situations where the hard drive
2509  // stops working, etc.
2510 
2511  // strOrigPlan is a String copy (a PGP-signed XML file, in string form) of
2512  // the original smart contract activation request...
2513  OTString strOrigPlan(*pOrigCronItem); // <====== Farther down in the code, I
2514  // attach this string to the receipts.
2515 
2516  // -------------- Make sure have both nyms loaded and checked out.
2517  // --------------------------------------------------
2518  // WARNING: The party's Nym could be also the Server Nym. But the Stash Nym
2519  // is ALWAYS the server.
2520  // In all of those different cases, I don't want to load the same file twice
2521  // and overwrite it with itself, losing
2522  // half of all my changes. I have to check all three IDs carefully and set
2523  // the pointers accordingly, and then operate
2524  // using the pointers from there.
2525 
2526  OTPseudonym thePartyNym;
2527 
2528  // Find out if party Nym is actually also the server nym.
2529  const bool bPartyNymIsServerNym =
2530  ((PARTY_USER_ID == SERVER_USER_ID) ? true : false);
2531 
2532  OTPseudonym* pPartyNym = nullptr;
2533  // OTPseudonym * pStashNym = pServerNym;
2534 
2535  const std::string str_party_id = strPartyUserID.Get();
2536  auto it_party = map_NymsAlreadyLoaded.find(str_party_id);
2537 
2538  if (map_NymsAlreadyLoaded.end() !=
2539  it_party) // found the party in list of Nyms that are already loaded.
2540  {
2541  pPartyNym = it_party->second;
2542  OT_ASSERT((nullptr != pPartyNym) &&
2543  (pPartyNym->CompareID(PARTY_USER_ID)));
2544  }
2545 
2546  // Figure out if party Nym is also Server Nym.
2547  if (bPartyNymIsServerNym) {
2548  // If the First Nym is the server, then just point to that.
2549  pPartyNym = pServerNym;
2550  }
2551  else if (nullptr == pPartyNym) // Else load the First Nym from storage, if
2552  // still not found.
2553  {
2554  thePartyNym.SetIdentifier(PARTY_USER_ID); // thePartyNym is pPartyNym
2555 
2556  if (!thePartyNym.LoadPublicKey()) {
2557  otErr << "OTSmartContract::StashFunds: Failure loading party Nym "
2558  "public key: " << strPartyUserID << "\n";
2559  FlagForRemoval(); // Remove it from future Cron processing, please.
2560  return false;
2561  }
2562 
2563  if (thePartyNym.VerifyPseudonym() &&
2564  thePartyNym.LoadSignedNymfile(*pServerNym)) // ServerNym here is not
2565  // thePartyNym's
2566  // identity, but merely
2567  // the signer on this
2568  // file.
2569  {
2570  otWarn << "OTSmartContract::StashFunds: Loading party Nym, since "
2571  "he apparently wasn't already loaded.\n"
2572  "(On a cron item processing, this is normal. But if you "
2573  "triggered a clause directly, then your Nym SHOULD be "
2574  "already loaded...)\n";
2575  pPartyNym = &thePartyNym; // <=====
2576  }
2577  else {
2578  otErr << "OTSmartContract::StashFunds: Failure loading or "
2579  "verifying party Nym public key: " << strPartyUserID
2580  << "\n";
2581  FlagForRemoval(); // Remove it from future Cron processing, please.
2582  return false;
2583  }
2584  }
2585  // Below this point, both Nyms are loaded and good-to-go.
2586 
2587  mapOfNyms map_ALREADY_LOADED; // I know I passed in one of these, but now I
2588  // have processed the Nym pointers (above) and
2589  // have better data here now.
2590  map_ALREADY_LOADED.insert(std::pair<std::string, OTPseudonym*>(
2591  strServerNymID.Get(),
2592  pServerNym)); // Add Server Nym to list of Nyms already loaded.
2593 
2594  auto it_temp = map_ALREADY_LOADED.find(strPartyUserID.Get());
2595  if (map_ALREADY_LOADED.end() == it_temp)
2596  map_ALREADY_LOADED.insert(std::pair<std::string, OTPseudonym*>(
2597  strPartyUserID.Get(),
2598  pPartyNym)); // Add party Nym to list of Nyms already loaded.
2599 
2600  // In this function, pStashNym and pServerNym are always the same.
2601 
2602  if (!pOrigCronItem->VerifyNymAsAgent(
2603  *pPartyNym, *pServerNym,
2604  // In case it needs to load the AUTHORIZING agent, and that agent
2605  // is already loaded, it will have access here.
2606  &map_ALREADY_LOADED)) {
2607  otErr << "OTSmartContract::StashFunds: Failed authorization for party "
2608  "Nym: " << strPartyUserID << "\n";
2609  FlagForRemoval(); // Remove it from Cron.
2610  return false;
2611  }
2612 
2613  // AT THIS POINT, I have: pServerNym, pPartyNym, and pStashNym,
2614  // PLUS: pStashAccount and pPartyAssetAcct
2615 
2616  // VerifySignature, VerifyContractID, and VerifyOwner have all been called
2617  // already
2618  // by this point. This is new:
2619  // (They might fall away in favor of this, once I start building.)
2620  //
2621  if (!VerifyNymAsAgentForAccount(*pPartyNym, *pPartyAssetAcct)) {
2622  otOut << "OTSmartContract::StashFunds: ERROR verifying ownership on "
2623  "source account.\n";
2624  FlagForRemoval(); // Remove it from future Cron processing, please.
2625  return false;
2626  }
2627  else {
2628  // Okay then, everything checks out. Let's add a receipt to the party's
2629  // inbox.
2630  // (No need for the stash's inbox -- the server owns it.)
2631 
2632  // Load the inbox in case it already exists
2633  OTLedger thePartyInbox(PARTY_USER_ID, PARTY_ACCT_ID, SERVER_ID);
2634 
2635  // ALL inboxes -- no outboxes. All will receive notification of
2636  // something ALREADY DONE.
2637  bool bSuccessLoadingPartyInbox = thePartyInbox.LoadInbox();
2638 
2639  // ...or generate them otherwise...
2640 
2641  if (true == bSuccessLoadingPartyInbox)
2642  bSuccessLoadingPartyInbox =
2643  thePartyInbox.VerifyAccount(*pServerNym);
2644  else
2645  otErr << "OTSmartContract::StashFunds: Failed trying to load "
2646  "party's inbox.\n";
2647  // OT_FAIL_MSG("ASSERT: TRYING TO GENERATE INBOX IN STASH
2648  // FUNDS!!!\n");
2649  // bSuccessLoadingPartyInbox =
2650  // thePartyInbox.GenerateLedger(PARTY_ACCT_ID, SERVER_ID,
2651  // OTLedger::inbox, true); // bGenerateFile=true
2652 
2653  if (!bSuccessLoadingPartyInbox) {
2654  otErr << "OTSmartContract::StashFunds: ERROR loading or generating "
2655  "inbox ledger.\n";
2656  }
2657  else {
2658  // Generate new transaction numbers for these new transactions
2659  int64_t lNewTransactionNumber = pCron->GetNextTransactionNumber();
2660 
2661  // OT_ASSERT(lNewTransactionNumber > 0); // this can be
2662  // my reminder.
2663  if (0 == lNewTransactionNumber) {
2664  otOut << "OTSmartContract::StashFunds: Aborted move: There are "
2665  "no more transaction numbers available in Cron.\n";
2666  // (Here I do NOT flag for removal.)
2667  return false;
2668  }
2669 
2671  thePartyInbox, OTTransaction::paymentReceipt,
2672  lNewTransactionNumber);
2673  // (No need to OT_ASSERT on the above new transaction since it
2674  // occurs in GenerateTransaction().)
2675 
2676  // The party's inbox will get a receipt with a new transaction ID on
2677  // it, owned by the server.
2678  // It will have a "In reference to" field containing the original
2679  // signed smart contract.
2680  // (with all party's signatures from their authorizing agents.)
2681 
2682  // set up the transaction item (each transaction may have multiple
2683  // items... but not in this case.)
2684  //
2686  *pTransParty, OTItem::paymentReceipt);
2687  OT_ASSERT(nullptr !=
2688  pItemParty); // may be unnecessary, I'll have to
2689  // check CreateItemFromTransaction.
2690  // I'll leave for now.
2691 
2692  pItemParty->SetStatus(OTItem::rejection); // the default.
2693 
2694  // const int64_t lPartyTransRefNo =
2695  // GetTransactionNum();
2696  const int64_t lPartyTransRefNo = GetOpeningNumber(PARTY_USER_ID);
2697 
2698  // Here I make sure that each receipt (each inbox notice) references
2699  // the original
2700  // transaction number that was used to set the cron item into
2701  // place...
2702  // This number is used to track all cron items. (All Cron items
2703  // require a transaction
2704  // number from the user in order to add them to Cron in the first
2705  // place.)
2706  //
2707  // The number is also used to uniquely identify all other
2708  // transactions, as you
2709  // might guess from its name.
2710  //
2711  // UPDATE: Notice I'm now looking up a different number based on the
2712  // UserID.
2713  // This is to support smart contracts, which have many parties,
2714  // agents, and accounts.
2715  //
2716  // pItemParty->SetReferenceToNum(lPartyTransRefNo);
2717  pTransParty->SetReferenceToNum(lPartyTransRefNo);
2718 
2719  // The TRANSACTION (a receipt in my inbox) will be sent with "In
2720  // Reference To" information
2721  // containing the ORIGINAL SIGNED SMARTCONTRACT. (With all parties'
2722  // original signatures on it.)
2723  //
2724  // Whereas the TRANSACTION ITEM will include an "attachment"
2725  // containing the UPDATED
2726  // SMART CONTRACT (this time with the SERVER's signature on it.)
2727  //
2728  // Here's the original one going onto the transaction:
2729  //
2730  pTransParty->SetReferenceString(strOrigPlan);
2731 
2732  //
2733  // MOVE THE DIGITAL ASSETS FROM ONE ACCOUNT TO ANOTHER...
2734  //
2735  // Calculate the amount and debit/ credit the accounts
2736  // Make sure each Account can afford it, and roll back in case of
2737  // failure.
2738 
2739  // Normally if you stash 10 clams, then your account is -10 clams,
2740  // and your stash is +10 clams.
2741  // Therefore if you unstash 5 gg, then your gg acct is +5 grams and
2742  // your stash is -5 grams.
2743  //
2744  // Thus if lAmount is > 0, as normal, that amount should be DEBITED
2745  // from the Party Acct, and CREDITED to the Stash Acct.
2746  // Whereas if lAmount were < 0, then that amount should be DEBITED
2747  // from the Stash Acct, and CREDITED to the Party Acct.
2748 
2749  bool bMoveParty = false;
2750  bool bMoveStash = false;
2751 
2752  if (bUnstashing) // Debit Stash, Credit Party
2753  {
2754  if (pStashAccount->GetBalance() >= lAbsoluteAmount) {
2755  // Debit the stash account.
2756  bMoveStash = pStashAccount->Debit(
2757  lAbsoluteAmount); // <====== DEBIT FUNDS
2758 
2759  // IF success, credit the party.
2760  if (bMoveStash) {
2761  bMoveParty = pPartyAssetAcct->Credit(
2762  lAbsoluteAmount); // <=== CREDIT FUNDS
2763 
2764  // Okay, we already took it from the stash account.
2765  // But if we FAIL to credit the party, then we need to
2766  // PUT IT BACK in the stash acct.
2767  // (EVEN THOUGH we'll just "NOT SAVE" after any failure,
2768  // so it's really superfluous.)
2769  //
2770  if (!bMoveParty) {
2771  bool bErr = pStashAccount->Credit(
2772  lAbsoluteAmount); // put the money back
2773 
2774  otErr << "OTSmartContract::StashFunds: While "
2775  "succeeded debiting the stash account, "
2776  "FAILED in: "
2777  "pPartyAssetAcct->Credit(lAbsoluteAmount);"
2778  " \n"
2779  "Also, tried to credit stash account back "
2780  "again. Result: "
2781  << (bErr ? "success" : "failure") << ".\n";
2782  }
2783  else { // SUCCESS!
2784  //
2785  bool bStashSuccess = pStashItem->DebitStash(
2786  lAbsoluteAmount); // we already verified above
2787  // that this stash item has
2788  // enough funds to
2789  // successfully debit.
2790 
2791  if (bStashSuccess)
2792  bSuccess = true;
2793  else
2794  otErr << "OTSmartContract::StashFunds: ERROR: "
2795  "Debited stash account and credited "
2796  "party account, but "
2797  "then unable to debit the stash "
2798  "record inside the smart contract "
2799  "itself.\n";
2800  }
2801  }
2802  else {
2803  otErr << "OTSmartContract::StashFunds: FAILED in: "
2804  "pStashAccount->Debit(lAbsoluteAmount);\n";
2805  }
2806  }
2807  }
2808  else // Debit party, Credit Stash
2809  {
2810  if (pPartyAssetAcct->GetBalance() >= lAbsoluteAmount) {
2811  // Debit the party account.
2812  bMoveParty = pPartyAssetAcct->Debit(
2813  lAbsoluteAmount); // <====== DEBIT FUNDS
2814 
2815  // IF success, credit the Stash.
2816  if (bMoveParty) {
2817  bMoveStash = pStashAccount->Credit(
2818  lAbsoluteAmount); // <=== CREDIT FUNDS
2819 
2820  // Okay, we already took it from the party account.
2821  // But if we FAIL to credit the Stash, then we need to
2822  // PUT IT BACK in the party acct.
2823  // (EVEN THOUGH we'll just "NOT SAVE" after any failure,
2824  // so it's really superfluous.)
2825  //
2826  if (!bMoveStash) {
2827  bool bErr = pPartyAssetAcct->Credit(
2828  lAbsoluteAmount); // put the money back
2829 
2830  otErr << "OTSmartContract::StashFunds: While "
2831  "succeeded debiting the asset account, "
2832  "FAILED in: "
2833  "pStashAccount->Credit(lAbsoluteAmount); "
2834  "\n"
2835  "Also, tried to credit asset account back "
2836  "again. Result: "
2837  << (bErr ? "success" : "failure") << ".\n";
2838  }
2839  else { // SUCCESS!
2840  //
2841  bool bStashSuccess = pStashItem->CreditStash(
2842  lAbsoluteAmount); // we already verified above
2843  // that this stash item has
2844  // enough funds to
2845  // successfully debit.
2846 
2847  if (bStashSuccess)
2848  bSuccess = true;
2849  else
2850  otErr << "OTSmartContract::StashFunds: ERROR: "
2851  "Debited party account and credited "
2852  "stash account, but "
2853  "then unable to credit the stash "
2854  "record inside the smart contract "
2855  "itself.\n";
2856  }
2857  }
2858  else {
2859  otErr << "OTSmartContract::StashFunds: FAILED in: "
2860  "pPartyAssetAcct->Debit(lAbsoluteAmount);\n";
2861  }
2862  }
2863  }
2864 
2865  // If ANY of these failed, then roll them all back and break.
2866  // (In fact we could just be checking bSuccess here, I wager.
2867  // Might as well be thorough.)
2868  //
2869  if (!bMoveParty || !bMoveStash) {
2870  // No need to roll back pStashItem here, since it is never
2871  // changed in the
2872  // first place unless BOTH of the above bools were successful.
2873 
2874  otErr << "OTSmartContract::StashFunds: Very strange! Funds "
2875  "were available but "
2876  "debit " << ((bUnstashing) ? "stash" : "party")
2877  << " or credit " << ((bUnstashing) ? "party" : "stash")
2878  << " failed while performing move.\n";
2879  // We won't save the files anyway, if this failed.
2880  bSuccess = false;
2881  }
2882 
2883  // DO NOT SAVE ACCOUNTS if bSuccess is false.
2884  // We only save these accounts if bSuccess == true.
2885  // (But we do save the inboxes either way, since payment failures
2886  // always merit an inbox notice.)
2887  //
2888  if (true == bSuccess) // The payment succeeded.
2889  {
2890  // The party needs to get a receipt in his inbox.
2891  //
2892  pItemParty->SetStatus(
2893  OTItem::acknowledgement); // pPartyAssetAcct
2894 
2895  const int64_t lReceiptAmount = (lAmount * (-1));
2896 
2897  // pItemParty->SetAmount(lAmount); // lAmount
2898  // is already negative or positive by the time it's passed into
2899  // this function.
2900  pItemParty->SetAmount(lReceiptAmount); // However, if we are
2901  // stashing 100, that
2902  // means my account is
2903  // -100. Therefore
2904  // multiply by (-1)
2905  // EITHER WAY.
2906  // pItemParty->SetAmount(lAbsoluteAmount*(-1));
2907  // // "paymentReceipt" is otherwise ambigious about whether you
2908  // are paying or being paid.
2909  // This is also like market receipts, which use negative and
2910  // positive amounts.
2911 
2912  otOut << "OTSmartContract::StashFunds: Move performed.\n";
2913 
2914  // (I do NOT save m_pCron here, since that already occurs after
2915  // this function is called.)
2916  }
2917  else // bSuccess = false. The payment failed.
2918  {
2919  pItemParty->SetStatus(OTItem::rejection); // pPartyAssetAcct
2920  // // These are
2921  // already initialized
2922  // to false.
2923  pItemParty->SetAmount(
2924  0); // No money changed hands. Just being explicit.
2925 
2926  otOut << "OTSmartContract::StashFunds: Move failed.\n";
2927  }
2928 
2929  // Everytime a payment processes, a receipt is put in the user's
2930  // inbox, containing a
2931  // CURRENT copy of the cron item (which took just money from the
2932  // user's acct, or not,
2933  // and either way thus updated its status -- so its internal state
2934  // has changed.)
2935  //
2936  // It will also contain a copy of the user's ORIGINAL signed cron
2937  // item, where the data
2938  // has NOT changed, (so the user's original signature is still
2939  // good.) Although in the case of
2940  // smart contracts, each party stores their own signed copy anyway,
2941  // so it doesn't matter as
2942  // much.
2943  //
2944  // In order for it to export the RIGHT VERSION of the CURRENT smart
2945  // contract, which has just
2946  // changed (above), then I need to re-sign it and save it first.
2947  // (The original version I'll
2948  // load from a separate file using
2949  // OTSmartContract::LoadCronReceipt(lTransactionNum).
2950  //
2951  // I should be able to call a method on the original cronitem, where
2952  // I ask it to verify a certain
2953  // nym as being acceptable to that cron item as an agent, based on
2954  // the signature of the original
2955  // authorizing agent for that party. UPDATE: I believe the function
2956  // described in this paragraph
2957  // is now done.
2958  //
2959 
2961  SignContract(*pServerNym);
2962  SaveContract();
2963 
2964  //
2965  // EVERYTHING BELOW is just about notifying the party, by dropping
2966  // the receipt in his
2967  // inbox. The rest is done. The two accounts and the inbox will all
2968  // be saved at the same time.
2969  //
2970  // The Smart Contract is entirely updated and saved by this point,
2971  // and Cron will
2972  // also be saved in the calling function once we return (no matter
2973  // what.)
2974  //
2975 
2976  // Basically I load up the INBOX, which is actually a LEDGER, and
2977  // then I create
2978  // a new transaction, with a new transaction item, for that ledger.
2979  // (That's where the receipt information goes.)
2980  //
2981 
2982  // The TRANSACTION will be sent with "In Reference To" information
2983  // containing the
2984  // ORIGINAL SIGNED SMART CONTRACT. (With both of the users' original
2985  // signatures on it.)
2986  //
2987  // Whereas the TRANSACTION ITEM will include an "attachment"
2988  // containing the UPDATED
2989  // SMART CONTRACT (this time with the SERVER's signature on it.)
2990 
2991  // (Lucky I just signed and saved the updated smart contract
2992  // (above), or it would still have
2993  // have the old data in it.)
2994 
2995  // I also already loaded the original smart contact. Remember this
2996  // from above,
2997  // near the top of the function:
2998  // OTSmartContract * pOrigCronItem = nullptr;
2999  // OTString strOrigPlan(*pOrigCronItem); // <====== Farther down
3000  // in the code, I attach this string to the receipts.
3001  // ... then lower down...
3002  // pTransParty->SetReferenceString(strOrigPlan);
3003  //
3004  // So the original plan is already loaded and copied to the
3005  // Transaction as the "In Reference To"
3006  // Field. Now let's add the UPDATED plan as an ATTACHMENT on the
3007  // Transaction ITEM:
3008  //
3009 
3010  //
3011 
3012  OTString strUpdatedCronItem(*this);
3013 
3014  // Set the updated cron item as the attachment on the transaction
3015  // item.
3016  // (With the SERVER's signature on it!)
3017  // (As a receipt for the party, so they can see their smartcontract
3018  // updating.)
3019  //
3020  pItemParty->SetAttachment(strUpdatedCronItem);
3021 
3022  // Success OR failure, either way I want a receipt in the inbox.
3023  // ===> But if FAILURE, I do NOT want to save the Accounts, JUST the
3024  // inbox!!
3025  //
3026  // (So the inbox happens either way, but the accounts are saved only
3027  // on success.)
3028 
3029  // sign the item
3030  pItemParty->SignContract(*pServerNym);
3031  pItemParty->SaveContract();
3032 
3033  // the Transaction "owns" the item now and will handle cleaning it
3034  // up.
3035  pTransParty->AddItem(*pItemParty);
3036  pTransParty->SignContract(*pServerNym);
3037  pTransParty->SaveContract();
3038 
3039  // Here, the transaction we just created is actually added to the
3040  // inbox ledger.
3041  // This happens either way, success or fail.
3042 
3043  thePartyInbox.AddTransaction(*pTransParty);
3044 
3045  // Release any signatures that were there before (They won't
3046  // verify anymore anyway, since the content has changed.)
3047  //
3048  thePartyInbox.ReleaseSignatures();
3049  thePartyInbox.SignContract(*pServerNym);
3050  thePartyInbox.SaveContract();
3051 
3052  pPartyAssetAcct->SaveInbox(thePartyInbox);
3053 
3054  // This corresponds to the AddTransaction() call just above.
3055  // These are stored in a separate file now.
3056  //
3057  pTransParty->SaveBoxReceipt(thePartyInbox);
3058 
3059  // If success, save the accounts with new balance. (Save inboxes
3060  // with receipts either way,
3061  // and the receipts will contain a rejection or acknowledgment
3062  // stamped by the Server Nym.)
3063  //
3064  if (true == bSuccess) {
3065  // SAVE THE ACCOUNTS.
3066 
3067  // Release any signatures that were there before (They won't
3068  // verify anymore anyway, since the content has changed.)
3069  //
3070  pPartyAssetAcct->ReleaseSignatures();
3071  pStashAccount->ReleaseSignatures();
3072 
3073  // Sign both of them.
3074  pPartyAssetAcct->SignContract(*pServerNym);
3075  pStashAccount->SignContract(*pServerNym);
3076 
3077  // Save both of them internally
3078  pPartyAssetAcct->SaveContract();
3079  pStashAccount->SaveContract();
3080 
3081  // TODO: Better rollback capabilities in case of failures here:
3082 
3083  // Save both accounts to storage.
3084  pPartyAssetAcct->SaveAccount();
3085  pStashAccount->SaveAccount();
3086  // NO NEED TO LOG HERE, since success / failure is already
3087  // logged above.
3088  }
3089  } // the inbox was successfully loaded or generated.
3090  } // By the time we enter this block, accounts and nyms are already loaded.
3091  // As we begin, inboxes are instantiated.
3092 
3093  // Either way, Cron should save, since it just updated.
3094  // The above function call WILL change this smart contract
3095  // and re-sign it and save it, no matter what. So I just
3096  // call this here to keep it simple:
3097 
3098  pCron->SaveCron(); // TODO No need to call this here if I can make sure it's
3099  // being called higher up somewhere
3100  // (Imagine a script that has 10 account moves in it -- maybe don't need to
3101  // save cron until
3102  // after all 10 are done. Or maybe DO need to do in between. Todo research
3103  // this. Optimization.)
3104  return bSuccess;
3105 }
3106 
3107 // Higher level. Can be executed from inside scripts.
3108 //
3109 // Returns success if funds were moved.
3110 // This function does not run any scripts, but it CAN be executed from within
3111 // the scripts.
3112 // Any movement of funds to-or-from any account will automatically try to
3113 // load/use the
3114 // appropriate authorizing agent for that account (or use him, if he's already
3115 // loaded on
3116 // this smart contract.)
3117 //
3118 
3119 bool OTSmartContract::MoveAcctFundsStr(std::string from_acct_name,
3120  std::string to_acct_name,
3121  std::string str_Amount)
3122 {
3123  OTCron* pCron = GetCron();
3124  OT_ASSERT(nullptr != pCron);
3125 
3126  OTPseudonym* pServerNym = pCron->GetServerNym();
3127  OT_ASSERT(nullptr != pServerNym);
3128 
3129  // Below this point, these are all good:
3130  //
3131  // pServerNym, pCron.
3132 
3133  if (str_Amount.size() < 1) {
3134  otOut << "OTSmartContract::MoveAcctFunds: Error: empty amount.\n";
3135  return false;
3136  }
3137 
3138  const int64_t lAmount = atol(str_Amount.c_str());
3139 
3140  if (lAmount <= 0) {
3141  otOut << "OTSmartContract::MoveAcctFunds: Error: lAmount cannot be 0 "
3142  "or <0. (Value passed in was " << lAmount << ".)\n";
3143  return false;
3144  }
3145 
3146  if (from_acct_name.size() <= 0) {
3147  otErr << "OTSmartContract::MoveAcctFunds: error: from_acct_name is "
3148  "non-existent.\n";
3149  return false;
3150  }
3151  if (to_acct_name.size() <= 0) {
3152  otErr << "OTSmartContract::MoveAcctFunds: error: to_acct_name is "
3153  "non-existent.\n";
3154  return false;
3155  }
3156 
3157  // Below this point, these are all good:
3158  //
3159  // from_acct_name,
3160  // to_acct_name,
3161  // pServerNym, pCron.
3162 
3163  OTPartyAccount* pFromAcct = GetPartyAccount(from_acct_name);
3164  OTPartyAccount* pToAcct = GetPartyAccount(to_acct_name);
3165 
3166  if (nullptr == pFromAcct) {
3167  otOut << "OTSmartContract::MoveAcctFunds: error: from_acct ("
3168  << from_acct_name << ") not found on any party.\n";
3169  otOut << "FULL CONTRACT: \n" << m_xmlUnsigned << " \n\n";
3170  return false;
3171  }
3172  if (nullptr == pToAcct) {
3173  otOut << "OTSmartContract::MoveAcctFunds: error: to_acct ("
3174  << to_acct_name << ") not found on any party.\n";
3175  otOut << "FULL CONTRACT: \n" << m_xmlUnsigned << " \n\n";
3176 
3177  return false;
3178  }
3179 
3180  // Below this point, these are all good:
3181  //
3182  // pFromAcct, from_acct_name,
3183  // pToAcct, to_acct_name,
3184  // pServerNym, pCron.
3185 
3186  OTAgent* pFromAgent =
3187  pFromAcct->GetAuthorizedAgent(); // This searches the account's party
3188  // for the account's authorized agent.
3189  OTAgent* pToAgent =
3190  pToAcct->GetAuthorizedAgent(); // (That way it's impossible to get an
3191  // agent for any other party.)
3192 
3193  if (nullptr == pFromAgent) {
3194  otOut << "OTSmartContract::MoveAcctFunds: error: authorized agent ("
3195  << pFromAcct->GetAgentName() << ") not found for from_acct ("
3196  << from_acct_name << ") on acct's party.\n";
3197  return false;
3198  }
3199  if (nullptr == pToAgent) {
3200  otOut << "OTSmartContract::MoveAcctFunds: error: authorized agent ("
3201  << pToAcct->GetAgentName() << ") not found for to_acct ("
3202  << to_acct_name << ") on acct's party.\n";
3203  return false;
3204  }
3205 
3206  if (!pFromAgent->IsAnIndividual()) {
3207  otOut << "OTSmartContract::MoveAcctFunds: error: authorized agent ("
3208  << pFromAcct->GetAgentName() << ") for from_acct ("
3209  << from_acct_name << ") is not an active agent.\n";
3210  return false;
3211  }
3212  if (!pToAgent->IsAnIndividual()) {
3213  otOut << "OTSmartContract::MoveAcctFunds: error: authorized agent ("
3214  << pToAcct->GetAgentName() << ") for to_acct (" << to_acct_name
3215  << ") is not an active agent.\n";
3216  return false;
3217  }
3218  //
3219  // Below this point, these are all good:
3220  //
3221  // pFromAcct, from_acct_name, pFromAgent,
3222  // pToAcct, to_acct_name, pToAgent,
3223  // pServerNym, pCron.
3224 
3225  OTParty* pFromParty = pFromAgent->GetParty();
3226  OTParty* pToParty = pToAgent->GetParty();
3227 
3228  if (nullptr == pFromParty) {
3229  otErr << "OTSmartContract::MoveAcctFunds: error: Party pointer nullptr "
3230  "on "
3231  "authorized agent (" << pFromAcct->GetAgentName()
3232  << ") for from_acct (" << from_acct_name << ").\n";
3233  return false;
3234  }
3235  if (nullptr == pToParty) {
3236  otErr << "OTSmartContract::MoveAcctFunds: error: Party pointer nullptr "
3237  "on "
3238  "authorized agent (" << pToAcct->GetAgentName()
3239  << ") for to_acct (" << to_acct_name << ").\n";
3240  return false;
3241  }
3242  //
3243  // Below this point, these are all good:
3244  //
3245  // pFromAcct, from_acct_name, pFromAgent, pFromParty,
3246  // pToAcct, to_acct_name, pToAgent, pToParty,
3247  // pServerNym, pCron.
3248 
3249  // Done: I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY SINGLE
3250  // TIME THE SCRIPT
3251  // CALLS MOVE FUNDS. Maybe that's good, but since technically this only
3252  // needs to be verified before the
3253  // first call, and not for EVERY call during any of a script's runs, I
3254  // should probably move this verification
3255  // higher, such as each time the OTCronItem triggers, plus each time a party
3256  // triggers a clause directly
3257  // through the API (server message). As long as those are covered, I will be
3258  // able to remove it from here
3259  // which should be a significant improvement for performance.
3260  // It will be at the bottom of those same functions that
3261  // "ClearTemporaryPointers()" should finally be called.
3262  //
3263  // FINAL DECISION: Redundant. See comment in
3264  // OTSmartContract::StashAcctFunds()
3265  //
3266  // A party might have many agents who are only voting groups, and cannot
3267  // actually sign for things
3268  // the way that nyms can. But at least ONE of those agents IS a Nym --
3269  // because there must have been
3270  // an authorizing agent who initially signed to accept the agreement, and
3271  // who fronted the opening
3272  // transaction number that activated it.
3273  //
3274  // Similarly, the authorized agent for any given party's account (each
3275  // account has its own authorized
3276  // agent) MUST be an active agent (an active agent is one with a
3277  // Nym--whether that Nym is representing
3278  // himself as the party, or whether representing some entity as an employee
3279  // in a role). Why MUST the
3280  // authorized agent be an active agent? Because when funds are moved, that
3281  // Nym must be loaded since
3282  // the account must show that Nym as a legal owner/agent. The MoveFunds will
3283  // cause a paymentReceipt to
3284  // drop into the Inbox for the relevant asset accounts, and that
3285  // paymentReceipt can ONLY be accepted
3286  // by that same Nym, who must use a transaction # that he signed for
3287  // previously and received through
3288  // his nymbox. There is actually no justification at all to take funds from
3289  // that account, since the
3290  // new balance has not yet been signed, UNLESS THE PAYMENTRECEIPT CONTAINS A
3291  // VALID, SIGNED AUTHORIZATION
3292  // FROM THE ACCOUNT HOLDER. *That* is why the authorizing agent must either
3293  // be the Party's Owner himself
3294  // (representing himself as an agent, which most will do) in which case he
3295  // will appear as the valid
3296  // owner of the account, OR he MUST be a Nym working in a Valid Role for an
3297  // Entity, where said Entity is
3298  // the valid owner on the account in question. Either OT, it will be
3299  // possible in OT for him to sign for
3300  // the paymentReceipts when they come in, and impossible for him to escape
3301  // liability for them.
3302  // (That's the idea anyway.)
3303  //
3304  // Since we know that the Authorized Agent for an account must be an ACTIVE
3305  // agent (one way or the other)
3306  // then we can error out here if he's not. We can then pass in his Nym ID
3307  //
3308 
3309  OTIdentifier theFromAgentID, theToAgentID;
3310  const bool bFromAgentID = pFromAgent->GetSignerID(theFromAgentID);
3311  const bool bToAgentID = pToAgent->GetSignerID(theToAgentID);
3312 
3313  if (!bFromAgentID) {
3314  otErr << "OTSmartContract::MoveAcctFunds: Failed to find FromAgent's "
3315  "Signer ID: " << pFromAgent->GetName() << " \n";
3316  return false;
3317  }
3318  if (!bToAgentID) {
3319  otErr << "OTSmartContract::MoveAcctFunds: Failed to find ToAgent's "
3320  "Signer ID: " << pToAgent->GetName() << " \n";
3321  return false;
3322  }
3323 
3324  if (!pFromAcct->GetAcctID().Exists()) {
3325  otErr << "OTSmartContract::MoveAcctFunds: Error: FromAcct has empty "
3326  "AcctID: " << from_acct_name << " \n";
3327  return false;
3328  }
3329  if (!pToAcct->GetAcctID().Exists()) {
3330  otErr << "OTSmartContract::MoveAcctFunds: Error: ToAcct has empty "
3331  "AcctID: " << to_acct_name << " \n";
3332  return false;
3333  }
3334 
3335  const OTIdentifier theFromAcctID(pFromAcct->GetAcctID()),
3336  theToAcctID(pToAcct->GetAcctID());
3337  //
3338  // BELOW THIS POINT, theFromAcctID, theFromAgentID, theToAcctID, and
3339  // theToAgentID are all available.
3340 
3341  // WE SET THESE HERE SO THE RECEIPT SHOWS, SUCCESS OR FAIL,
3342  // WHO THE INTENDED SENDER / RECIPIENT ARE FOR THAT RECEIPT.
3343  //
3345 
3346  theFromAgentID.GetString(m_strLastSenderUser); // This is the last User ID
3347  // of a party who SENT money.
3348  theFromAcctID.GetString(m_strLastSenderAcct); // This is the last Acct ID of
3349  // a party who SENT money.
3350  theToAgentID.GetString(m_strLastRecipientUser); // This is the last User ID
3351  // of a party who RECEIVED
3352  // money.
3353  theToAcctID.GetString(m_strLastRecipientAcct); // This is the last Acct ID
3354  // of a party who RECEIVED
3355  // money.
3356 
3357  mapOfNyms map_Nyms_Already_Loaded;
3358  RetrieveNymPointers(map_Nyms_Already_Loaded);
3359 
3360  bool bMoved = MoveFunds(map_Nyms_Already_Loaded, lAmount, theFromAcctID,
3361  theFromAgentID, theToAcctID, theToAgentID);
3362  if (!bMoved) {
3363  otOut << "OTSmartContract::MoveAcctFunds: Failed in call to MoveFunds. "
3364  "from_acct: " << from_acct_name
3365  << " to_acct: " << to_acct_name << "\n";
3366  return false;
3367  }
3368 
3369  return true;
3370 }
3371 
3372 // This is called by OTCronItem::HookRemovalFromCron
3373 //
3374 // (After calling this method, HookRemovalFromCron then calls
3375 // onRemovalFromCron.)
3376 //
3378  const int64_t& lNewTransactionNumber,
3379  OTPseudonym& theOriginator,
3380  OTPseudonym* pActingNym) // AKA "pRemover"
3381  // in any other
3382  // onFinalReceipt.
3383 // Could be nullptr.
3384 {
3385  OTCron* pCron = GetCron();
3386  OT_ASSERT(nullptr != pCron);
3387 
3388  OTPseudonym* pServerNym = pCron->GetServerNym();
3389  OT_ASSERT(nullptr != pServerNym);
3390 
3391  const OTString strServerID(GetServerID());
3392 
3393  // The finalReceipt Item's ATTACHMENT contains the UPDATED Cron Item.
3394  // (With the SERVER's signature on it!)
3395  //
3396  OTString strUpdatedCronItem(*this);
3397  OTString* pstrAttachment = &strUpdatedCronItem;
3398 
3399  const OTString strOrigCronItem(theOrigCronItem);
3400 
3401  // IF server is originator and/or remover then swap it in for it/them so I
3402  // don't load it twice.
3403  // (already handled before this function is called.)
3404 
3405  // THIS FUNCTION:
3406  //
3407  //
3408  // LOOP through all parties.
3409  // For each party:
3410  // If party is server or originator or ActingNym, etc then set pointer
3411  // appropriately for that party.
3412  // Find opening and closing numbers for that party.
3413  // Drop finalReceipt to Inboxes for each asset account, using closing
3414  // numbers.
3415  // Drop finalReceipt to Nymbox for that party, using opening number.
3416  //
3417  // A similar process should happen whenever ANY contract action occurs. (Not
3418  // just finalReceipt)
3419  // We loop through all the parties and give them a receipt in the relevant
3420  // accounts.
3421  // And perhaps all notices should be numbered (similar to request number) so
3422  // that
3423  // people can prove which notices they have received.
3424  // Receipts are given based on?
3425  // The asset accounts that are CHANGED should definitely get an
3426  // agreementReceipt for the
3427  // balance change. + All Nymboxes should receive a notice at that time.
3428  // They should receive
3429  // additional notice for any change in any variable as well. Maybe let
3430  // parties register for
3431  // various notices.
3432  // What about if a clause processes, but no asset accounts are changed, (no
3433  // inbox notice)
3434  // and no other variables are changed (no nymbox notices at all...) In that
3435  // case,
3436  // no other receipts are dropped, right? There will be some standard by
3437  // which DIRTY flags
3438  // are set onto the various parties and asset accounts, and then notices
3439  // will be sent based
3440  // upon those.
3441  //
3442  // For those, instead of:
3443  // "theOriginator" (GetSenderUserID()) and "pRemover" and pRecipient,
3444  //
3445  // We would have:
3446  // "theOriginator" (GetSenderUserID()) and "pActingNym" and pParty /
3447  // pPartyNym (for Party[0..n])
3448  //
3449  // Just like here:
3450  //
3451 
3452  for (auto& it : m_mapParties) {
3453  OTParty* pParty = it.second;
3454  OT_ASSERT_MSG(nullptr != pParty,
3455  "Unexpected nullptr pointer in party map.");
3456 
3457  // The Nym who is actively requesting to remove a cron item will be
3458  // passed in as pActingNym.
3459  // However, sometimes there is no Nym... perhaps it just expired and
3460  // pActingNym is nullptr.
3461  // The originating Nym (if different than pActingNym) is loaded up.
3462  // Otherwise theOriginator
3463  // just points to *pActingNym also.
3464  //
3465  OTPseudonym* pPartyNym = nullptr;
3466  std::unique_ptr<OTPseudonym> thePartyNymAngel;
3467 
3468  // See if the serverNym is an agent on this party.
3469  //
3470  if (pParty->HasAuthorizingAgent(*pServerNym)) // This should set the
3471  // temp nym ptr inside the
3472  // agent also, so I don't
3473  // have to search twice.
3474  {
3475  pPartyNym = pServerNym; // Just in case the party's agent's Nym is
3476  // also the server Nym.
3477  }
3478  //
3479  // If pActingNym is NOT nullptr, and HE is an agent on this party...
3480  // then set the pointer accordingly.
3481  //
3482  else if ((nullptr != pActingNym) &&
3483  pParty->HasAuthorizingAgent(*pActingNym)) // There is only one
3484  // authorizing agent
3485  // per party.
3486  {
3487  pPartyNym = pActingNym; // <======== now both pointers are set (to
3488  // same Nym). DONE!
3489  }
3490 
3491  // Still not found?
3492  if (nullptr == pPartyNym) {
3493  // Of all of a party's Agents, the "authorizing agent" is the one
3494  // who originally activated
3495  // the agreement for this party (and fronted the opening trans#.) If
3496  // we're ending the agreement,
3497  // Then we need to free that number from him. (Even if he was since
3498  // fired from the role!)
3499  //
3500  // Perhaps need to figure out if the Role itself stores the opening
3501  // number, and if so, treat
3502  // the Nym's signature as the role's, even though the Nym himself
3503  // doesn't actually store the #.
3504  // Anyway, I'll deal with that when I get to entities and roles.
3505  // Todo.
3506  //
3507  pPartyNym = pParty->LoadAuthorizingAgentNym(*pServerNym);
3508  thePartyNymAngel.reset(pPartyNym);
3509  }
3510 
3511  // Every party SHOULD have an authorizing agent (otherwise how did that
3512  // party sign on in the first
3513  // place??) So this should never fail. That's why there's an error
3514  // message below if it's still nullptr.
3515  //
3516 
3517  if ((nullptr != pPartyNym) && (pParty->GetOpeningTransNo() > 0) &&
3518  // Todo: once entities and roles are added, Parties should have
3519  // their OWN "verify" function
3520  // (Instead of me having to directly find the Nym and verify it
3521  // myself.)
3522  //
3523  pPartyNym->VerifyIssuedNum(
3524  strServerID,
3525  pParty->GetOpeningTransNo()) // <=====================
3526  ) {
3527  // The Nym (server side) stores a list of all opening and closing
3528  // cron #s.
3529  // So when the number is released from the Nym, we also take it off
3530  // that list.
3531  //
3532  std::set<int64_t>& theIDSet = pPartyNym->GetSetOpenCronItems();
3533  theIDSet.erase(pParty->GetOpeningTransNo());
3534 
3535  // the RemoveIssued call means the original transaction# (to find
3536  // this cron item on cron) is now CLOSED.
3537  // But the Transaction itself is still OPEN. How? Because the
3538  // CLOSING number is still signed out.
3539  // The closing number is also USED, since the smart contract was
3540  // initially activated, but it remains
3541  // ISSUED, until the final receipt itself is accepted during a
3542  // process inbox.
3543  //
3544  pPartyNym->RemoveIssuedNum(*pServerNym, strServerID,
3545  pParty->GetOpeningTransNo(),
3546  false); // bSave=false
3547  pPartyNym->SaveSignedNymfile(*pServerNym);
3548  }
3549  else {
3550  otErr
3551  << "OTSmartContract::" << __FUNCTION__
3552  << ": Failed verifying "
3553  "pPartyNym != nullptr && pParty->GetOpeningTransNo() > 0 && "
3554  " "
3555  "pPartyNym->VerifyIssuedNum(pParty->GetOpeningTransNo())\n";
3556  }
3557 
3558  // NOTIFY ALL AGENTS for this party, with a copy of the finalReceipt in
3559  // their Nymbox.
3560  //
3561  // TOdo: if the above block fails, should I still go dropping these
3562  // receipts?
3563  //
3564  if ((false ==
3566  lNewTransactionNumber, // new, owned by the server.
3567  // For notices.
3568  strOrigCronItem, nullptr, pstrAttachment, pPartyNym))) {
3569  otErr << "OTSmartContract::" << __FUNCTION__
3570  << ": Failure dropping final receipt into nymbox for even a "
3571  "single agent.\n";
3572  }
3573 
3574  // So the same Nym doesn't get loaded twice on accident. (We pass in
3575  // pointers to nyms that
3576  // are already loaded, so the called function can use them instead of
3577  // loading, if it came
3578  // to that.)
3579  //
3580  // typedef std::map <std::string, OTPseudonym *> mapOfNyms;
3581 
3582  mapOfNyms nym_map;
3583 
3584  // pServerNym
3585  {
3586  const OTIdentifier theServerNymID(*pServerNym);
3587  const OTString strServerNymID(theServerNymID);
3588 
3589  if (nym_map.end() == nym_map.find(strServerNymID.Get()))
3590  nym_map.insert(std::pair<std::string, OTPseudonym*>(
3591  strServerNymID.Get(), pServerNym));
3592  }
3593 
3594  // theOriginator
3595  {
3596  const OTIdentifier theOriginatorNymID(theOriginator);
3597  const OTString strOriginatorNymID(theOriginatorNymID);
3598 
3599  if (nym_map.end() == nym_map.find(strOriginatorNymID.Get()))
3600  nym_map.insert(std::pair<std::string, OTPseudonym*>(
3601  strOriginatorNymID.Get(), &theOriginator));
3602  }
3603 
3604  if (nullptr != pActingNym) {
3605  const OTIdentifier theActingNymID(*pActingNym);
3606  const OTString strActingNymID(theActingNymID);
3607 
3608  if (nym_map.end() == nym_map.find(strActingNymID.Get()))
3609  nym_map.insert(std::pair<std::string, OTPseudonym*>(
3610  strActingNymID.Get(), pActingNym));
3611  }
3612 
3613  if (nullptr != pPartyNym) {
3614  const OTIdentifier thePartyNymID(*pPartyNym);
3615  const OTString strPartyNymID(thePartyNymID);
3616 
3617  if (nym_map.end() == nym_map.find(strPartyNymID.Get()))
3618  nym_map.insert(std::pair<std::string, OTPseudonym*>(
3619  strPartyNymID.Get(), pPartyNym));
3620  }
3621 
3622  // NOTIFY the agent for EACH ACCOUNT listed by this party,
3623  // with a copy of the finalReceipt in the Inbox for each asset acct.
3624  //
3625  // Also for each, if he has a Nym (HE SHOULD), and if
3626  // (CLOSING_NUMBER_HERE > 0), then call:
3627  //
3628  // pNym->VerifyIssuedNum(strServerID, lClosingNumber)
3629  // (This happens in OTAgent::DropFinalReceipt, FYI.)
3630  //
3631 
3632  if (false ==
3633  pParty->DropFinalReceiptToInboxes(
3634  &nym_map, // contains any Nyms who might already be
3635  // loaded, mapped by ID.
3636  strServerID, *pServerNym, lNewTransactionNumber,
3637  strOrigCronItem, nullptr, pstrAttachment)) {
3638  otErr << "OTSmartContract::onFinalReceipt: Failure dropping final "
3639  "receipt into all inboxes. (Missed at least one.)\n";
3640  }
3641 
3642  pParty->ClearTemporaryPointers();
3643  }
3644 }
3645 
3646 // OTCron calls this regularly, which is my chance to expire, etc.
3647 // Return True if I should stay on the Cron list for more processing.
3648 // Return False if I should be removed and deleted.
3650 {
3651  OT_ASSERT(nullptr != GetCron());
3652 
3653  // Right now Cron is called 10 times per second.
3654  // I'm going to slow down all trades so they are once every
3655  // GetProcessInterval()
3656  // Todo: Create separate lists in Cron. 10*/sec list, 1/second list, 1 min
3657  // list, 1 hour, 1 day, 1 month.
3658  // That way I'm not looping through ALL cron items 10*/second, but only the
3659  // ones who are paying for those
3660  // kinds of resources. (Different lists will cost different server fees.)
3661  //
3662  if (GetLastProcessDate() > OT_TIME_ZERO) {
3663  // Default ProcessInternal is 1 second, but Trades will use 10 seconds,
3664  // and Payment
3665  // Plans will use an hour or day. Smart contracts are currently 30
3666  // seconds. (For testing.)
3667  //
3670  return true;
3671  }
3672  // Keep a record of the last time this was processed.
3673  // (NOT saved to storage, only used while the software is running.)
3674  // (Thus no need to release signatures, sign contract, save contract, etc.)
3676 
3677  // END DATE --------------------------------
3678  // First call the parent's version (which this overrides) so it has
3679  // a chance to check its stuff.
3680  // Currently it calls IsExpired().
3681  //
3682  if (!ot_super::ProcessCron()) {
3683  otLog3 << "Cron job has expired.\n";
3684  return false; // It's expired or flagged for removal--remove it from
3685  // Cron.
3686  }
3687 
3688  // START DATE --------------------------------
3689  // Okay, so it's not expired. But might not have reached START DATE yet...
3690  if (!VerifyCurrentDate())
3691  return true; // The Payment Plan is not yet valid, so we return. BUT, we
3692  // also
3693  // return TRUE, so it will STAY on Cron until it BECOMES valid.
3694 
3695  // Make sure there are transaction numbers available in Cron.
3696  // (Can't do anything without those....)
3697  //
3698  if (GetCron()->GetTransactionCount() < 1) {
3699  otOut << "Failed to process smart contract: Cron is out of transaction "
3700  "numbers!\n";
3701  return true;
3702  }
3703 
3704  // Make sure, if the script set a timer, that we don't process Cron until
3705  // that timer
3706  // is reached. (If the timer's not set, then we go ahead and process every
3707  // time.)
3708  //
3709  const time64_t& tNextProcessDate = GetNextProcessDate();
3710 
3711  if (tNextProcessDate > OT_TIME_ZERO) // IF there is a timer set (as to when
3712  // the next "onProcess" should
3713  // occur)...
3714  {
3715  if (OTTimeGetCurrentTime() <=
3716  tNextProcessDate) // AND if the current time has NOT YET reached
3717  // that date (the date in the timer)...
3718  {
3719  // ...Then RETURN (since the timer hasn't popped yet)
3720  // But return TRUE, so that this cron item stays active for now.
3721  //
3722  return true;
3723  }
3724  else // else it HAS now reached the official timer date...
3725  {
3726  SetNextProcessDate(OT_TIME_ZERO); // Therefore timer has triggered,
3727  // so we will continue processing.
3728  } // We also reset timer to 0 again since it has now "binged".
3729  } // Continuing on....
3730 
3731  // Execute the scripts (clauses) that have registered for this hook.
3732 
3733  const std::string str_HookName(SMARTCONTRACT_HOOK_ON_PROCESS);
3734  mapOfClauses theMatchingClauses;
3735 
3736  if (GetHooks(str_HookName, theMatchingClauses)) {
3737  otOut << "Cron: Processing smart contract clauses for hook: "
3738  << SMARTCONTRACT_HOOK_ON_PROCESS << " \n";
3739 
3741  theMatchingClauses); // <============================================
3742  }
3743 
3744  if (IsFlaggedForRemoval()) {
3745  otLog3 << "OTSmartContract::ProcessCron: Removing smart contract from "
3746  "cron processing...\n";
3747  return false; // false means "remove this cron item from cron"
3748  }
3749 
3750  return true;
3751 }
3752 
3753 // virtual
3754 void OTSmartContract::SetDisplayLabel(const std::string* pstrLabel)
3755 {
3756  m_strLabel.Format("smartcontract trans# %lld, clause: %s",
3758  (nullptr != pstrLabel) ? pstrLabel->c_str() : "");
3759 }
3760 
3762  OTString* pParam) // someday
3763  // pParam could
3764  // be a
3765  // stringMap
3766  // instead of a
3767  // single
3768  // param.
3769 {
3770  // Loop through the clauses passed in, and execute them all.
3771  for (auto& it_clauses : theClauses) {
3772  const std::string str_clause_name = it_clauses.first;
3773  OTClause* pClause = it_clauses.second;
3774  OT_ASSERT((nullptr != pClause) && (str_clause_name.size() > 0));
3775  OTBylaw* pBylaw = pClause->GetBylaw();
3776  OT_ASSERT(nullptr != pBylaw);
3777 
3778  // By this point, we have the clause we are executing as pClause,
3779  // and we have the Bylaw it belongs to, as pBylaw.
3780 
3781  const std::string str_code =
3782  pClause->GetCode(); // source code for the script.
3783  const std::string str_language =
3784  pBylaw->GetLanguage(); // language it's in. (Default is "chai")
3785 
3786  std::shared_ptr<OTScript> pScript =
3787  OTScriptFactory(str_language, str_code);
3788 
3789  std::unique_ptr<OTVariable> theVarAngel;
3790 
3791  //
3792  // SET UP THE NATIVE CALLS, REGISTER THE PARTIES, REGISTER THE
3793  // VARIABLES, AND EXECUTE THE SCRIPT.
3794  //
3795  if (pScript) {
3796  // Register the special server-side native OT calls we make
3797  // available to all scripts.
3798  //
3800 
3801  // Register all the parties with the script.
3802  //
3803  for (auto& it : m_mapParties) {
3804  const std::string str_party_name = it.first;
3805  OTParty* pParty = it.second;
3806  OT_ASSERT((nullptr != pParty) && (str_party_name.size() > 0));
3807 
3808  pScript->AddParty(str_party_name, *pParty); // This also
3809  // registers all of
3810  // Party's accounts
3811  // with pScript.
3812  }
3813 
3814  // Also need to loop through the Variables on pBylaw and register
3815  // those as well.
3816  //
3818  *pScript); // This also sets all the variables as CLEAN so we
3819  // can check for dirtiness after execution.
3820 
3821  // A parameter might also be passed in, so we add that to the script
3822  // as well.
3823  // (Like if a client is sending a triggerClause message to a server,
3824  // and passing
3825  // a string parameter to that clause as input.)
3826  //
3827  const std::string str_Name("param_string");
3828  std::string str_Value("");
3829 
3830  // See if param_string variable is already found on the bylaw...
3831  //
3832  if (nullptr !=
3833  pBylaw->GetVariable(str_Name)) // disallow duplicate names.
3834  {
3835  otErr << "OTSmartContract::ExecuteClauses: While preparing to "
3836  "run smartcontract trans# " << GetTransactionNum()
3837  << ", clause: " << str_clause_name
3838  << ". Error: Parameter variable named " << str_Name
3839  << " already exists. (Skipping the parameter actually "
3840  "passed in.)\n";
3841  }
3842  else // The param_string variable isn't already there. (So we add
3843  // it as blank, if a value wasn't passed in.)
3844  {
3845  if (nullptr != pParam) // if a param was passed in...
3846  str_Value = pParam->Get();
3847  // else (it's already "")
3848 
3849  OTVariable* pVar = new OTVariable(str_Name, str_Value,
3851  OT_ASSERT(nullptr != pVar);
3852  theVarAngel.reset(pVar);
3853 
3854  pVar->RegisterForExecution(*pScript); // This causes pVar to
3855  // keep a pointer to the
3856  // script so it can remove
3857  // itself from the script
3858  // upon destruction.
3859  // pScript->AddVariable(str_Name, *pVar);
3860  }
3861 
3862  // TEMP FOR TESTING (HARDCODED CLAUSE NAME HERE...)
3863  // OTVariable theReturnVal("return_val", false); //
3864  // initial value is: false.
3865 
3866  SetDisplayLabel(&str_clause_name);
3867 
3868  pScript->SetDisplayFilename(m_strLabel.Get());
3869 
3870  if (!pScript->ExecuteScript()) // If I passed theReturnVal
3871  // in here, then it'd be
3872  // assumed a bool is expected
3873  // to be returned inside it.
3874  // if (false ==
3875  // pScript->ExecuteScript((str_clause_name.compare("process_clause")
3876  // == 0) ? &theReturnVal : nullptr))
3877  {
3878  otErr << "OTSmartContract::ExecuteClauses: Error while running "
3879  "smartcontract trans# " << GetTransactionNum()
3880  << ", clause: " << str_clause_name << " \n\n";
3881  }
3882  else
3883  otOut << "OTSmartContract::ExecuteClauses: Success executing "
3884  "smartcontract trans# " << GetTransactionNum()
3885  << ", clause: " << str_clause_name << " \n\n";
3886 
3887  // For now, I've decided to allow ALL clauses to trigger
3888  // on the hook. The flag only matters after
3889  // they are done, and not between scripts. Otherwise
3890  // problems could arise, such as order of execution.
3891  // Remember, there is nothing stopping people from using
3892  // their own variables and ending all behavior
3893  // after that flag is set. Todo security: revisit this
3894  // just in case.
3895  //
3896  }
3897  else {
3898  otErr << "OTSmartContract::ExecuteClauses: Error instantiating "
3899  "script!\n";
3900  }
3901  }
3902 
3903  // "Important" variables.
3904  // (If any of them have changed, then I need to notice the parties.)
3905  //
3906  // TODO: Fix IsDirtyImportant() so that it checks for changed STASHES
3907  // as well. (Or have another function to do it, which is also called here.)
3908  //
3909  // I'd like to get to where I can just call IsDirty() here, and then SAVE
3910  // CRON HERE,
3911  // so I'm not having to save it after EACH change, which is currently
3912  // occuring in the
3913  // StashAcctFunds / MoveAcctFunds functions. Todo.
3914  //
3915  if (IsDirtyImportant()) // This tells us if any "Important" variables
3916  // have changed since executing the scripts.
3917  {
3918  OTCron* pCron = GetCron();
3919  OT_ASSERT(nullptr != pCron);
3920 
3921  OTPseudonym* pServerNym = pCron->GetServerNym();
3922  OT_ASSERT(nullptr != pServerNym);
3923 
3924  const int64_t lNewTransactionNumber = pCron->GetNextTransactionNumber();
3925 
3926  // OT_ASSERT(lNewTransactionNumber > 0); // this can be my
3927  // reminder.
3928  if (0 == lNewTransactionNumber) {
3929  otErr << "OTSmartContract::ExecuteClauses: ** ERROR: Notice not "
3930  "sent to parties, since no "
3931  "transaction numbers were available!\n";
3932  }
3933  else {
3935  SignContract(*pServerNym);
3936  SaveContract();
3937 
3938  const OTString strReference(*this);
3939  bool bDroppedNotice = SendNoticeToAllParties(
3940  true, // bSuccessMsg=true
3941  *pServerNym, GetServerID(), lNewTransactionNumber,
3942  strReference); // pstrNote and pstrAttachment aren't used in
3943  // this case.
3944 
3945  otOut << __FUNCTION__
3946  << ": FYI, 'Important' variables were changed during the "
3947  "execution of this script.\n"
3948  << (bDroppedNotice ? "Success" : "Failure")
3949  << " dropping notifications into all parties' nymboxes.\n";
3950  }
3951  }
3952 }
3953 
3954 // The server calls this when it wants to know if a certain party is allowed to
3955 // cancel
3956 // the entire contract (remove it from Cron).
3957 // This function tries to answer that question by checking for a callback script
3958 // called:
3959 // callback_party_may_cancel_contract
3960 // If the callback script exists, then it calls that for the answer. Otherwise
3961 // the default
3962 // return value is: true (as long as he's a legitimate party.)
3963 // Script coders may also call "party_may_cancel_contract()" from within a
3964 // script, which
3965 // will call this function, which will trigger the script
3966 // callback_party_may_cancel_contract(),
3967 // etc.
3968 //
3969 bool OTSmartContract::CanCancelContract(std::string str_party_name)
3970 {
3971  OTCron* pCron = GetCron();
3972  OT_ASSERT(nullptr != pCron);
3973 
3974  OTPseudonym* pServerNym = pCron->GetServerNym();
3975  OT_ASSERT(nullptr != pServerNym);
3976 
3977  OTParty* pParty = GetParty(str_party_name);
3978 
3979  if (nullptr == pParty) {
3980  otOut
3981  << "OTSmartContract::CanCancelContract: Unable to find this party: "
3982  << str_party_name << "\n";
3983  return false;
3984  }
3985  // Below this point, pParty is good.
3986 
3987  // ...This WILL check to see if pParty has its Opening number verified as
3988  // issued.
3989  // (If the opening number is > 0 then VerifyPartyAuthorization() is smart
3990  // enough to verify it.)
3991  //
3992  // To KNOW that a party has the right to even ASK the script to cancel a
3993  // contract, MEANS that
3994  // (1) The party is listed as a party on the contract. (2) The party's copy
3995  // of that contract
3996  // is signed by the authorizing agent for that party. and (3) The opening
3997  // transaction number for
3998  // that party is verified as issued for authorizing agent. (2 and 3 are both
3999  // performed at the same
4000  // time, in VerifyPartyAuthorization(), since the agent may need to be
4001  // loaded in order to verify
4002  // them.) 1 is already done by this point, as it's performed above.
4003  //
4004  // Done: notice this code appears in CanCancelContract() (this function) as
4005  // well as
4006  // OTScriptable::CanExecuteClause.
4007  // Therefore I can see that THIS VERIFICATION CODE WILL GET CALLED EVERY
4008  // SINGLE TIME THE SCRIPT
4009  // CALLS ANY CLAUSE OR OT NATIVE FUNCTION. Since technically this only
4010  // needs to be verified before the
4011  // first call, and not for EVERY call during any of a script's runs, I
4012  // should probably move this verification
4013  // higher, such as each time the OTCronItem triggers, plus each time a party
4014  // triggers a clause directly
4015  // through the API (server message). As long as those are covered, I will be
4016  // able to remove it from here
4017  // which should be a significant improvement for performance.
4018  // It will be at the bottom of those same functions that
4019  // "ClearTemporaryPointers()" should finally be called.
4020  //
4021  // Also todo: Need to implement MOVE CONSTRUCTORS and MOVE COPY
4022  // CONSTRUCTORS all over the place,
4023  // once I'm sure C++0x build environments are available for all of the
4024  // various OT platforms. That should
4025  // be another great performance boost!
4026  //
4027  // FINAL DECISION: Redundant. See comment in
4028  // OTSmartContract::StashAcctFunds()
4029  //
4030 
4031  // IF NO CALLBACK IS PROVIDED, The default answer to this function is:
4032  // YES, this party MAY cancel this contract! (Assuming he's a real
4033  // party,
4034  // which we have verified by this point.)
4035  //
4036  // But... first we check to see if this OTScriptable has a clause named:
4037  // "callback_party_may_cancel_contract"
4038  // ...and if so, we ask the CALLBACK to make the decision instead. This way,
4039  // people can define
4040  // in their own scripts any rules they want about which parties may cancel
4041  // the contract.
4042 
4043  //
4044  const std::string str_CallbackName(SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL);
4045 
4046  OTClause* pCallbackClause =
4047  GetCallback(str_CallbackName); // See if there is a script clause
4048  // registered for this callback.
4049 
4050  if (nullptr != pCallbackClause) // Found it! There's a clause registered for
4051  // this callback. Let's call it...
4052  {
4053  otOut << "OTSmartContract::CanCancelContract: Found script for: "
4054  << SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL << ". Asking...\n";
4055 
4056  // The function we're IN defaults to TRUE, if there's no script
4057  // available.
4058  // However, if the script IS available, then our default return value
4059  // starts as FALSE.
4060  // (The script itself will then have to set it to true, if that's what
4061  // it wants.)
4062  //
4063  OTVariable theReturnVal("return_val", false);
4064 
4065  OTVariable param1(
4066  "param_party_name", str_party_name,
4067  OTVariable::Var_Constant); // script can reference param_party_name
4068 
4069  mapOfVariables theParameters;
4070  theParameters.insert(
4071  std::pair<std::string, OTVariable*>("param_party_name", &param1));
4072 
4073  if (false ==
4075  *pCallbackClause, theParameters,
4076  theReturnVal)) // <============================================
4077  {
4078  otErr << "OTSmartContract::CanCancelContract: Error while running "
4079  "callback script "
4080  << SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL << ", clause "
4081  << pCallbackClause->GetName() << " \n";
4082  return false;
4083  }
4084  else {
4085  otOut << "OTSmartContract::CanCancelContract: Success executing "
4086  "callback script "
4087  << SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL
4088  << ", clause: " << pCallbackClause->GetName() << ".\n\n";
4089 
4090  return theReturnVal.CopyValueBool();
4091  }
4092 
4093  }
4094  else {
4095  otOut
4096  << "OTSmartContract::CanCancelContract: Unable to find script for: "
4098  << ". Therefore, default return value is: TRUE.\n";
4099  }
4100 
4101  return true;
4102 }
4103 
4107 {
4108  // You don't just go willy-nilly and remove a cron item from a market unless
4109  // you check first
4110  // and make sure the Nym who requested it actually has said number (or a
4111  // related closing number)
4112  // signed out to him on his last receipt...
4113  //
4114  // Note: overrode parent method and NOT calling it.
4115  // We do it our own way here, and call a script if it's available.
4116 
4117  // IT'S ASSUMED that the opening and closing numbers WILL be verified in
4118  // order to
4119  // insure they are CURRENTLY ISSUED.
4120  //
4121  // theNym.VerifyIssuedNum(strServerID, GetOpeningNum();
4122  // theNym.VerifyIssuedNum(strServerID, GetClosingNum();
4123  //
4124  // The default version OTCronItem does this for theNym, and the PaymentPlan
4125  // version
4126  // has to be a little smarter: it has to figure out whether theNym is the
4127  // Sender or Recipient,
4128  // so that it knows where to verify the numbers from, before allowing theNym
4129  // to do the removal.
4130  //
4131  //
4132  // ===> THIS version (OTSmartContract) will look up pParty using theNym via:
4133  // OTParty * OTScriptable::FindPartyBasedOnNymAsAgent(const OTPseudonym&
4134  // theNym, OTAgent ** ppAgent=nullptr);
4135  //
4136  // ...Then it WILL check to see if pParty has its Opening number verified as
4137  // issued.
4138  // ...It COULD ALSO loop the partyaccounts and see if pAgent is authorized
4139  // agent for any of them.
4140  // (If so, pAcct->VerifyClosingNumber() or pAgent->VerifyClosingNumber()
4141  // as well.)
4142  //
4143  //
4144  OTAgent* pAgent = nullptr;
4146  theNym, &pAgent); // This sets a pointer to theNym inside pAgent, so
4147  // pParty can use it later.
4148 
4149  if (nullptr == pParty) {
4150  otOut << "OTSmartContract::CanRemoveItemFromCron: Warning: theNym is "
4151  "not an agent "
4152  "for any party to this contract, yet tried to remove it.\n";
4153  return false;
4154  }
4155  OT_ASSERT(nullptr != pAgent); // With one comes the other.
4156 
4157  // Below this point, pAgent is not only good, but it contains a secret
4158  // hidden pointer now to theNym.
4159  // That way, when the SCRIPT asks the party to verify issued number, without
4160  // even having a reference to theNym,
4161  // the party will internally still be able to handle it. This always works
4162  // in cases where it's needed because
4163  // we used theNym to look up pParty, and the lookup function is what sets
4164  // that pointer. That's why I clean
4165  // the pointer again after I'm done. (AT THE BOTTOM OF THIS FUNCTION.)
4166  //
4167 
4168  // NOTE: You can see OTCronItem looks up the relevant numbers by trying to
4169  // figure out if theNym
4170  // is sender or receiver, and then calling these methods:
4171  // if (GetCountClosingNumbers() < 1)
4172  // if (GetRecipientCountClosingNumbers() < 2)
4173  // Etc.
4174  //
4175  // But OTSmartContract doesn't use those functions, except where it has to
4176  // in order to
4177  // work within the existing OTCronItem system. (That is, the ORIGINATOR who
4178  // actually activates
4179  // a smart contract must still provide at least an opening number, which is
4180  // stored in the old
4181  // system and used by it.)
4182  // Instead, OTSmartContract keeps its own records (via its parent class
4183  // OTScriptable) of all the
4184  // parties to the contract, and all of their opening transaction #s, as well
4185  // as the accounts that
4186  // are party to the contract, and the closing transaction #s for each of
4187  // those.
4188  //
4189  // ===> Therefore, when it comes to verifying whether the Nym has CERTAIN
4190  // RIGHTS regarding the
4191  // contract, OTSmartContract doesn't actually use the old system for that,
4192  // but instead queries its
4193  // own, superior system.
4194  //
4195  // In order to prevent infinite recursion I think I will be adding THAT code
4196  // into:
4197  // OTSmartContract::CanCancelContract(party_name)
4198 
4199  bool bReturnValue = false;
4200  bool bPartyHasName = false;
4201  const std::string str_party_name = pParty->GetPartyName(&bPartyHasName);
4202 
4203  if (bPartyHasName &&
4204  CanCancelContract(str_party_name)) // Here is where it calls the
4205  // script, inside this call.
4206  {
4207  otOut << "OTSmartContract::CanRemoveItemFromCron: Looks like theNym "
4208  "represents a party (" << str_party_name
4209  << ") and "
4210  "IS allowed by this contract to cancel it whenever he "
4211  "chooses.\n";
4212  bReturnValue = true;
4213  }
4214 
4215  pParty->ClearTemporaryPointers(); // FindPartyBasedOnNymAsAgent() set the
4216  // party's agent's nym pointer to theNym.
4217  // This clears it.
4218 
4219  return bReturnValue;
4220 }
4221 
4222 // Server-side, need to verify ALL parties upon activation.
4223 // Client-side, need to verify CURRENT list of parties before "the next party"
4224 // signs on.
4225 // May not be able to tell the difference, in code. I can verify that the
4226 // present ones are good,
4227 // but I can't guarantee that others aren't referenced in the script code,
4228 // without some kind of
4229 // "trial run" of the script, or parsing of it.
4230 //
4231 // Therefore no point verifying originator here -- let's verify it here for ANY
4232 // of the parties, and
4233 // let the server explicitly verify the trans#s instead of relying on this
4234 // function to do it. That way
4235 // I can use this function even in cases where I'm not able to verify the
4236 // trans#s (such as on the
4237 // client side.) SERVER WILL STILL NEED TO VERIFY those numbers....
4238 //
4239 // Server will also want to verify that originator IS a party (this function
4240 // won't do it.)
4241 //
4242 // bool OTSmartContract::VerifySmartContract(OTPseudonym& theNym)
4243 //{
4244 // Need to verify:
4245 //
4246 // 1) That the opening/closing trans# on this CronItem match ONE of the parties.
4247 // (Maybe not verifier.)
4248 // (Parties to trades and payments each have their own opening numbers.
4249 // Therefore you can with scripts. But only one can activate.)
4250 // With trades, each Nym has their own cron item and #. With payment plans,
4251 // there is only one cron item, and the sender is the
4252 // activator. Since he is the one paying, the number used is his. The other
4253 // guy still gets receipts, but the code is smart
4254 // enough to create his receipts using HIS opening number, which he still has
4255 // to provide up front. (Hmm.. in implementation that's not true...)
4256 // Anyway, continuing: But those receipts contain
4257 // COPIES of the original cron item that was ACTIVATED by the sender, and has
4258 // his trans# on it.
4259 // Still: the cron item is saved to storage under a specific number, right?
4260 // Scripts must be smart enough to drop a receipt for
4261 // each party where the Opening Number comes from THAT PARTY, and where a
4262 // closing number comes from one of his accts.
4263 //
4264 // 2) Verify this details against ALL parties copies.
4265 //
4266 // 3) If an optional list of Nyms is passed in, then verify all their signatures
4267 // as well. hmm.
4268 //
4269 // May not even need this function. Could be the new ones above are enough to
4270 // cover it all.
4271 //
4272 
4273 // ABOVE Makes sure that all parties' signed copies are equivalent to my own
4274 // (*this)
4275 //
4276 // Once this is established, then BELOW verifies all the data on (*this) against
4277 // the actual Nyms passed in.
4278 //
4279 // Finally, the signature for each is verified against his own copy.
4280 //
4281 
4282 // For smart contract:
4283 //
4284 // 1) Assume verifier could be any one of the parties, not necessarily the
4285 // originator
4286 
4287 // TO WORK WITHIN THE EXISTING CRON SYSTEM, the originator's Opening and Closing
4288 // #s must be set
4289 // and available onto THIS CRON ITEM, so that GetTransactionNum() is the opening
4290 // and GetCountClosingNUmbers()
4291 // contains at least 1 number. Thus: if originator does not have an asset
4292 // account in his party, we fail to activate!!
4293 // Originator MUST have an asset account...
4294 // Why? Who cares about the closing numbers except for custom code for specific
4295 // things like trades? We only REALLY
4296 // care about the closing number when we need to put it into an asset account's
4297 // inbox as a finalReceipt. AHHH But
4298 // the server DOES drop copies of all finalReceipts into your NYMBOX as well, as
4299 // a NOTICE, so you can get the news faster.
4300 // And the SAME NUMBER is put onto that receipt, which you receive in your
4301 // Nymbox even if you HAVE NO asset account.
4302 // Perhaps you should provide one for your Nym AND for all your accounts. That
4303 // way your Nym can get a copy of all those
4304 // notices, but even without any asset accounts, he STILL gets a notice
4305 // onFinalReceipt with his own special number on it.
4306 //
4307 // THE ONLY DIFFERENCE IS: With inbox finalReceipts, the closing number stays
4308 // open until you process your inbox to accept it.
4309 // You receive a notice of that same receipt in your Nymbox already, so that you
4310 // know to stop using your OPENING number. This is
4311 // because it's possible for it to appear out of the blue, and your transactions
4312 // for all accts would stop working unless you knew
4313 // which inbox to examine for the finalReceipt that must have appeared. So it
4314 // goes into Nymbox so you only have to check one place.
4315 // WHEREAS WITH SMART CONTRACT NYMBOX NOTICES, the Nymbox notice can also
4316 // contain a CLOSING # for that NYM ITSELF. So it sees
4317 // when the script has ended. HMM. Why not have the Nym's Opening # be verified
4318 // to start, and then that SAME # go into the Nym's
4319 // Nymbox on the finalReceipt? The Nym can then close it out on his side (thanks
4320 // to that notice) the same as it does now with other cron items.
4321 // The "closing #" that would also be on the nymbox notice is unneeded in this
4322 // case, since there are no asset accounts, and the Nym just needed
4323 // notice that his opening number was free again.
4324 //
4325 // Therefore, to work within existing cron system, it should be easy to simply
4326 // add the Opening Number for originator, AND
4327 // to set the Closing Number on the Cron Item to be the originator's opening
4328 // number, in cases where he has no asset accounts.
4329 // I'm curious where that may ever even be needed -- I bet it's only there to
4330 // provide a common location, since the other cron item
4331 // types all happen to use it. I will endeavor to work within a paradigm where
4332 // closing numbers are only needed for asset accounts
4333 // and where Cron Items are still functional without them, for Nyms using
4334 // contracts without asset accounts.
4335 //
4336 // UPDATE: in actual implementation, I resolved this with the simple requirement
4337 // that the Nym who ACTIVATES a
4338 // smart contract, must be the authorized agent for at least ONE account for his
4339 // party, in that contract! This
4340 // simple requirement, which would probably be true anyway, in practice, insures
4341 // that there are legitimate opening
4342 // and closing transaction numbers available from the Nym who actually activates
4343 // the contract.
4344 // (That Nym, however, is still subject to the rules of the contract.)
4345 
4346 // Here are my notes of what is needed here:
4347 //
4348 // return true; // Success!
4349 //}
4350 //
4351 
4352 // Old thoughts
4353 // Note: agents will have restrictable permissions. Should be overridable in the
4354 // role,
4355 // in the agent itself (in the party), etc. Like a registered agent -- he can
4356 // ONLY activate
4357 // things (and sign for them...) After that, the passive mechanism of the group
4358 // voting takes
4359 // over for all future meetings/decisions.
4360 // But someone must sign at first. This can be a "registered agent" if you
4361 // want, with limited
4362 // authority, only allowed to activate.
4363 
4364 // theNym is trying to activate the smart contract, and has
4365 // supplied transaction numbers and a user/acct ID. ==> theNym definitely IS the
4366 // owner of the account... that is
4367 // verified in OTServer::NotarizeTransaction(), before it even knows what KIND
4368 // of transaction it is processing!
4369 // (For all transactions.) So by the time OTServer::NotarizeSmartContract() is
4370 // called, we know that much.
4371 //
4372 // But for all other parties, we do not know this, so we still need to loop them
4373 // all, etc to verify this crap,
4374 // at least once. (And then maybe I can lessen some of the double-checking, for
4375 // optimization purposes, once
4376 // we've run this gamut.)
4377 //
4378 // One thing we still do not know, until VerifySmartContract is called, is
4379 // whether theNym really IS a valid
4380 // agent for this contract, and whether all the other agents are valid, and
4381 // whether the accounts are validly
4382 // owned by the agents they list, and whether the authorizing agent for each
4383 // party has signed their own copy,
4384 // and whether the authorizing agent for each party provided a valid opening
4385 // number--which must be recorded
4386 // as consumed--and whether the authorized agent for each account provided a
4387 // valid closing number, which likewise
4388 // must be recorded. (Set bBurnTransNo to true if you want to enforce the stuff
4389 // about the opening and closing #s)
4390 //
4392  OTAccount& theAcct,
4393  OTPseudonym& theServerNym,
4394  bool bBurnTransNo)
4395 {
4396  OTAgent* pAuthAgent = nullptr;
4397  OTParty* pAuthParty = FindPartyBasedOnNymAsAuthAgent(theNym, &pAuthAgent);
4398 
4399  if (nullptr == pAuthParty) {
4400  OTString strNymID;
4401  theNym.GetIdentifier(strNymID);
4402  otOut << __FUNCTION__
4403  << ": Unable to find a party in this smart contract, based "
4404  "on theNym (" << strNymID << ") as authorizing agent.\n";
4405  return false;
4406  }
4407  OT_ASSERT(nullptr !=
4408  pAuthAgent); // If it found the party, then it DEFINITELY
4409  // should have set the agent pointer.
4410  // BELOW THIS POINT, pAuthAgent and pAuthParty and both good pointers.
4411  // Furthermore, we know that theNym
4412  // really is the authorizing agent for one of the parties to the contract.
4413 
4414  const OTString strServerID(
4415  GetServerID()); // the serverID has already been verified by this time,
4416  // in OTServer::NotarizeSmartContract()
4417 
4418  mapOfNyms map_Nyms_Already_Loaded; // The list of Nyms that were already
4419  // instantiated before this function was
4420  // called.
4421  RetrieveNymPointers(map_Nyms_Already_Loaded); // now theNym is on this
4422  // map. (His party
4423  // already has a pointer
4424  // to him since he is
4425  // the activator.)
4426 
4427  mapOfNyms map_Nyms_Loaded_In_This_Function; // The total list of Nyms that
4428  // were instantiated inside this
4429  // function (and must be
4430  // deleted.)
4431 
4432  mapOfAccounts map_Accts_Already_Loaded; // The list of Accounts that were
4433  // already instantiated before this
4434  // function was called.
4435  const OTString strAcctID(theAcct.GetRealAccountID());
4436  map_Accts_Already_Loaded.insert(std::pair<std::string, OTAccount*>(
4437  strAcctID.Get(), &theAcct)); // now theAcct is on this map.
4438 
4439  mapOfAccounts map_Accts_Loaded_In_This_Function; // The total list of Accts
4440  // that were instantiated
4441  // inside this function
4442  // (and must be deleted.)
4443 
4444  bool bAreAnyInvalidParties = false;
4445  std::set<OTParty*> theFailedParties; // A set of pointers to parties who
4446  // failed verification.
4447 
4448  // LOOP THROUGH ALL PARTIES AND VERIFY THEM.
4449  for (auto& it_party : m_mapParties) {
4450  const std::string str_party_name = it_party.first;
4451  OTParty* pParty = it_party.second;
4452  OT_ASSERT_MSG(nullptr != pParty,
4453  "OTSmartContract::VerifySmartContract: "
4454  "Unexpected nullptr pointer in party "
4455  "map.\n");
4456 
4457  /*
4458  -- Load up the authorizing agent's Nym, if not already loaded. (Why? To
4459  verifySignature. Also, just to have
4460  it loaded so I don't have to load it twice in case it's needed for
4461  verifying one/some of the accts.) So really:
4462  -- Verify each party, that the authorizing agent and signature are all
4463  good. (I think I have this already...)
4464  -- Definitely during this, need to make sure that the contents of the
4465  signed version match the contents of the main version, for each signer.
4466  -- Verify that the authorizing agent actually has the opening
4467  transaction # for the party issued to him. (Do I have this?....)
4468 
4469  -- REMOVE the Opening transaction # for each agent.
4470  (leaving it as issued, but no longer as "available to be used on
4471  another transaction".)
4472 
4473  THE ABOVE is all accomplished via VerifyPartyAuthorization()..
4474 
4475  Next:
4476 
4477  -- Loop through all the asset accounts
4478  -- For each, get a pointer to the authorized agent and verify the
4479  CLOSING number for that asset acct. (I have something like this?...)
4480 
4481  -- Since we're looping through all the agents, and looping through all
4482  the asset accounts, and checking the agent for each asset account,
4483  then we might as well make sure that each agent is a legit agent for
4484  the party, and that each account has a legit agent lording over it.
4485  (Don't I do something like that already?)
4486  */
4487 
4488  bool bToBurnOrNotToBurn = bBurnTransNo;
4489 
4490  // If we're burning a number, but THIS party has the same opening # as
4491  // the smart contract itself, then don't bother verifying / burning this
4492  // specific number (since it's been done already, higher-up.)
4493  //
4494  if (bBurnTransNo && // If this party's opening number is the SMART
4495  // CONTRACT's opening number, then this party
4496  (GetTransactionNum() ==
4497  pParty->GetOpeningTransNo())) // MUST be the ACTIVATOR. (No need to
4498  // mark his trans# as IN USE since
4499  // already done earlier.)
4500  {
4501  // In cases where we're supposed to burn the transaction number, we
4502  // do that
4503  // for ALL parties EXCEPT the one who has the same Opening# as the
4504  // SmartContract
4505  // has for its GetTransactionNum(). Why? Because that one was
4506  // already burned, when
4507  // the activating party (pParty) activated the smart contract. At
4508  // that time, the normal
4509  // transaction system inside OTServer burned the # as part of its
4510  // process before even
4511  // calling NotarizeSmartContract(). Therefore, by this point, we
4512  // ASSUME that party's
4513  // opening num has already JUST been verified, and we skip it,
4514  // (continuing to verify
4515  // all the others.)
4516 
4517  bToBurnOrNotToBurn = false;
4518  }
4519 
4520  mapOfNyms map_Nyms_NewlyLoaded, map_Nyms_Already_Loaded_AS_OF_NOW;
4521 
4522  map_Nyms_Already_Loaded_AS_OF_NOW.insert(
4523  map_Nyms_Already_Loaded.begin(), map_Nyms_Already_Loaded.end());
4524  map_Nyms_Already_Loaded_AS_OF_NOW.insert(
4525  map_Nyms_Loaded_In_This_Function.begin(),
4526  map_Nyms_Loaded_In_This_Function.end());
4527 
4528  const bool bIsPartyAuthorized = VerifyPartyAuthorization(
4529  *pParty, // The party that supposedly is authorized for this
4530  // supposedly executed agreement.
4531  theServerNym, // For verifying signature on the authorizing Nym,
4532  // when loading it
4533  strServerID, // For verifying issued num, need the serverID the #
4534  // goes with.
4535  &map_Nyms_Already_Loaded_AS_OF_NOW, &map_Nyms_NewlyLoaded,
4536  bToBurnOrNotToBurn); // bBurnTransNo = true (default is false)
4537 
4538  map_Nyms_Loaded_In_This_Function.insert(map_Nyms_NewlyLoaded.begin(),
4539  map_Nyms_NewlyLoaded.end());
4540 
4541  // By this point, we've verified that pParty->GetOpeningTransNo() really
4542  // is ISSUED to pParty.
4543  // After all, you can Verify a Party's Authorization even after the
4544  // smart contract has been activated.
4545  // But in THIS function we also want to verify TRANSACTION num (not just
4546  // VerifyIssuedNum()) because
4547  // this is where that number is actually being BURNED for each one.
4548  // Since VerifyPartyAuthorization() ALREADY has the Nym loaded up for
4549  // verification, I'm going
4550  // to pass in a boolean arg to verify the Transaction Num as well, and
4551  // burn it. (for this very purpose.)
4552  //
4553  // Due to this, We don't want to stop this loop just because one of the
4554  // parties failed. We want to go ahead
4555  // and burn ALL the opening numbers for the remainder of the parties, so
4556  // that they have a consistent rule (the
4557  // opening number is considered burned and gone after a failed
4558  // activation attempt, though the closing numbers
4559  // are salvageable.) Otherwise they would never know, upon receiving a
4560  // server failure reply, whether their
4561  // opening number was to still be considered valid -- or not.
4562  //
4563  if (!bIsPartyAuthorized) {
4564  otOut << __FUNCTION__ << ": Party " << str_party_name
4565  << " does NOT verify as authorized! \n";
4566  bAreAnyInvalidParties = true; // We let them all go through, but we
4567  // still take notice that at least one
4568  // failed.
4569 
4570  theFailedParties.insert(pParty); // (So we can skip them in the loop
4571  // below. Meaning THEIR closing #s
4572  // also don't get marked as "used",
4573  // which is another reason for
4574  // clients to just harvest the
4575  // number in that case and consider
4576  // it as clean, since the server
4577  // is.)
4578  // return false; // see above comment. We still allow all
4579  // parties to burn their opening #s, to keep things consistent for
4580  // the client GUI code.
4581  }
4582  }
4583 
4584  // NEXT: THE ACCOUNTS
4585  //
4586  // We loop through the parties again, now knowing they are all authorized.
4587  // For each party, we call pParty->LoadAndVerifyAgentNyms(). This way, they
4588  // will
4589  // all be loaded up already for when we verify the accounts. Similarly we
4590  // call
4591  // pParty->LoadAndVerifyAssetAccounts(), so that all the accounts are loaded
4592  // up
4593  // as well. (We at least need to check their signatures...) At that point,
4594  // all
4595  // of the agent nyms AND accounts have been loaded! (And verified internally
4596  // against
4597  // themselves, such as their signature, etc.)
4598  //
4599  // From there, I need to verify the Party's Ownership over the account, as
4600  // well as
4601  // verify that the authorized agent listed for each account actually has
4602  // signer rights
4603  // over that account, and verify the closing transaction #s for each account
4604  // against its
4605  // authorized agent.
4606  //
4607  bool bAreAnyInvalidAccounts = false;
4608 
4609  /*
4610  NOTE on syncronicity...
4611 
4612  Above, we burned all the opening numbers for ALL the various nyms, even if
4613  there was some failure halfway through
4614  the verification process. This in order to make it easy to tell whether,
4615  for you, that number is still good or not.
4616 
4617  Similarly, what about the closing numbers (below) ? They are not instantly
4618  BURNED just for the ATTEMPT (as the
4619  opening numbers were) but they are still marked below as "USED BUT STILL
4620  ISSUED."
4621 
4622  if (bAreAnyInvalidParties) just above insures that the below code will not
4623  run if there are any invalid parties.
4624  That means that if "the message succeeded but transaction failed" due to
4625  invalid parties, then the closing numbers
4626  will never be seen by the server and thus never marked as "USED BUT STILL
4627  ISSUED." Instead, they would still be
4628  considered "ISSUED AND AVAILABLE."
4629 
4630  Based on that:
4631  If some FAILURE occurs below, as above, it still completes the loop in
4632  order to have consistent results for the
4633  closing transaction numbers, for all parties. So we know that success or
4634  fail, if the below code runs, the closing
4635  number is DEFINITELY marked as "USED BUT STILL ISSUED" for ALL parties,
4636  whereas if the below code does not run, the
4637  closing number for all parties is definitely still marked as "ISSUED AND
4638  AVAILABLE" (as far as this message is
4639  concerned.)
4640 
4641  Thus, there is still an inconsistency. When a client is later trying to
4642  interpret which transaction numbers to "claw
4643  back", he will have to harvest back the closing numbers SOMETIMES, based on
4644  WHY the transaction failed verification,
4645  and thus he cannot rely on a "transaction failed" state to give him a
4646  reliable answer to that question.
4647 
4648  However, we must keep in mind that these CLOSING numbers have NOT been
4649  burned -- they ARE still on the client's local
4650  list for his nym as "USED BUT STILL ISSUED." If the client harvests them
4651  back each time consistently, what will happen?
4652  The client will look at each closing number, see if it's on his local
4653  "issued" list (which it is) and then will re-add
4654  it to his "available" list as well. So is it really available on the server
4655  side? The answer is: sometimes.
4656 
4657  SOLUTION?
4658  1. Above, cache a list of all the parties who failed verification.
4659  2. Allow the code below to run, even if some parties have failed.
4660  3. Change the code below to skip failed parties while verifying accounts.
4661  (Using afore-mentioned list to make this possible.)
4662  4. Move the "if failed parties, return false" block BELOW this loop, in
4663  conjunction with the invalid accounts block.
4664 
4665  This will guarantee that closing numbers are consistently marked as "USED
4666  BUT STILL ISSUED" on the server side, no matter
4667  HOW the transaction has failed. (At least it will then be consistent.)
4668 
4669  However, if the transaction HAS failed, then all those closing numbers, if
4670  the clients are to claw them back, must be
4671  marked as available once again on the server side, as well! And if the
4672  clients are NOT to claw them back for future use,
4673  then how will they ever close them out? The server already won't allow the
4674  numbers to be used again, since they were
4675  marked as "used but still issued". But the transaction is ALREADY closed
4676  (it failed.)
4677 
4678  SOLUTIONS?
4679  -- Server could burn the closing numbers for failed transactions, vs
4680  marking them as "used but issued" when the transaction
4681  is successful. That way any client getting notice of the failure would
4682  DEFINITELY know that those numbers were burned, and
4683  could sync himself accordingly. (We definitely need to notice all
4684  parties as well, in this case, since they will need
4685  to discard the burned numbers after that point, in order to avoid going
4686  out-of-sync.)
4687 
4688  -- Server could also, in the event of transaction failure, mark the closing
4689  numbers as "available again, like new!"
4690  This way clients could clearly determine whether to burn their numbers
4691  or mark them as available again, purely based
4692  on the transaction's failure state. (State meaning the message itself is
4693  successful, and transaction could be success or fail.)
4694  Clients will not go out of sync in this case, if they fail to adjust to
4695  match the server. Well, they would be out of
4696  sync, but not the kind that prevents you from doing new transactions.
4697  (Rather, it's the kind where you have certain numbers
4698  signed out forever and you can never get rid of them.) Therefore, a
4699  notice is ALSO needed for this case.
4700 
4701  -- I know notices are already being sent upon activation, but I need to
4702  research that more closely now and determine the
4703  exact circumstances of these notices. Clearly a notice is REQUIRED, no
4704  matter which above option I choose!
4705 
4706  Thought: If notice is REQUIRED either way, perhaps the clients can just
4707  assume X unless a notice is received? For example,
4708  a client could just ASSUME the closing number is "used but still issued"
4709  unless notice is received to the contrary. This IS
4710  how the state would be if the transaction were successful, yet if it had
4711  failed, or hadn't been activated yet, the client
4712  also wouldn't experience any syncing issues by making this assumption.
4713 
4714  Clearly the server HAS to, in the event of transaction failure, mark the
4715  closing numbers either as "available again, like new!"
4716  or it has to mark them as BURNED, but either way, it's an additional piece
4717  the server has to do (up until now it has only
4718  marked them as "used but still issued.") What I can see is the server HAS
4719  to do something about those numbers, and it HAS
4720  to notify all the parties whether that transaction succeeded or failed, and
4721  then those parties HAVE to fix their client-side
4722  transaction count BASED on whether that transaciton succeeded or failed.
4723 
4724  Therefore:
4725 
4726  1. Implement the above 4-step solution.
4727  2. Do something about all the closing numbers, if activation fails.
4728  (Keep the nyms loaded until that is done, so as not to have to load them
4729  twice.)
4730  3. Make sure the parties are consistently noticed either way.
4731  4. Make sure the parties are syncing their numbers properly based on these
4732  notices.
4733 
4734 
4735  WOW, eh? But I believe that smart contracts are the most complicated case,
4736  so this has got to be the worst of it, now handled :-)
4737 
4738  Another note: If we assume the server burns the closing numbers, then the
4739  clients will suddenly be out-of-sync and unable
4740  to process transactions until they receive and process the notice of this
4741  failure. But if we instead assume that the server
4742  "makes new" those closing numbers, then the clients will remain in sync
4743  regardless of notice, and they only need to harvest
4744  the numbers upon notice, just so they can use them again, and they will not
4745  experience any "out of sync failures" along the
4746  way. Thus, it is preferable for the server to "make those numbers new
4747  again!" in the event of activation failure, AND to notice
4748  the parties of this so that they can do likewise.
4749  One way to notice them is to drop the "message succeeded but transaction
4750  failed" server reply into ALL of their Nymboxes,
4751  and not just the activator's. But not sure if that's safe... hm.
4752 
4753  */
4754 
4755  for (auto& it_party : m_mapParties) {
4756  const std::string str_party_name = it_party.first;
4757  OTParty* pParty = it_party.second;
4758  OT_ASSERT_MSG(nullptr != pParty,
4759  "Unexpected nullptr pointer in party map.");
4760 
4761  // SKIP FAILED PARTIES...
4762  //
4763  auto it_failed = theFailedParties.find(pParty);
4764 
4765  if (theFailedParties.end() != it_failed) // this means pParty was found
4766  // on the FAILED list. (So we
4767  // can skip it here.)
4768  {
4769  otOut << __FUNCTION__ << ": FYI, at least one party ("
4770  << str_party_name
4771  << ") has failed, and right now I'm skipping verification of "
4772  "his asset accounts.\n";
4773  continue;
4774  }
4775 
4776  mapOfNyms map_Nyms_NewlyLoaded, map_Nyms_Already_Loaded_AS_OF_NOW;
4777 
4778  map_Nyms_Already_Loaded_AS_OF_NOW.insert(
4779  map_Nyms_Already_Loaded.begin(), map_Nyms_Already_Loaded.end());
4780  map_Nyms_Already_Loaded_AS_OF_NOW.insert(
4781  map_Nyms_Loaded_In_This_Function.begin(),
4782  map_Nyms_Loaded_In_This_Function.end());
4783 
4784  // After calling this, map_Nyms_NewlyLoaded will contain pointers to
4785  // Nyms that MUST BE CLEANED UP.
4786  // LoadAndVerifyAgentNyms will not bother loading any Nyms which appear
4787  // on map_Nyms_Already_Loaded.
4788  //
4789  const bool bAgentsLoaded = pParty->LoadAndVerifyAgentNyms(
4790  theServerNym, map_Nyms_Already_Loaded_AS_OF_NOW, // Nyms it won't
4791  // bother loading
4792  // 'cause they are
4793  // loaded already.
4794  map_Nyms_NewlyLoaded); // Nyms it had to load itself, and thus that
4795  // YOU must clean up afterwards.
4796  map_Nyms_Loaded_In_This_Function.insert(map_Nyms_NewlyLoaded.begin(),
4797  map_Nyms_NewlyLoaded.end());
4798  if (!bAgentsLoaded) {
4799  otOut << __FUNCTION__
4800  << ": Failed trying to Load and Verify Agent Nyms for party: "
4801  << str_party_name << "\n";
4802  bAreAnyInvalidAccounts = true; // We let them all go through, so
4803  // there is consistent output, but we
4804  // still take notice that at least
4805  // one failed.
4806  }
4807 
4808  mapOfAccounts map_Accts_NewlyLoaded, map_Accts_Already_Loaded_AS_OF_NOW;
4809 
4810  map_Accts_Already_Loaded_AS_OF_NOW.insert(
4811  map_Accts_Already_Loaded.begin(), map_Accts_Already_Loaded.end());
4812  map_Accts_Already_Loaded_AS_OF_NOW.insert(
4813  map_Accts_Loaded_In_This_Function.begin(),
4814  map_Accts_Loaded_In_This_Function.end());
4815 
4816  // After calling this, map_Accts_NewlyLoaded will contain pointers to
4817  // Accts that MUST BE CLEANED UP.
4818  // LoadAndVerifyAssetAccounts will not bother loading any Accts which
4819  // appear on map_Accts_Already_Loaded.
4820  //
4821  const bool bAcctsLoaded = pParty->LoadAndVerifyAssetAccounts(
4822  theServerNym, strServerID,
4823  map_Accts_Already_Loaded_AS_OF_NOW, // Accts it won't bother loading
4824  // 'cause they are loaded
4825  // already.
4826  map_Accts_NewlyLoaded); // Accts it had to load itself, and thus
4827  // that YOU must clean up afterwards.
4828 
4829  map_Accts_Loaded_In_This_Function.insert(map_Accts_NewlyLoaded.begin(),
4830  map_Accts_NewlyLoaded.end());
4831  if (!bAcctsLoaded) {
4832  otOut
4833  << __FUNCTION__
4834  << ": Failed trying to Load and Verify Asset Accts for party: "
4835  << str_party_name << "\n";
4836  bAreAnyInvalidAccounts = true; // We let them all go through, so
4837  // there is consistent output, but we
4838  // still take notice that at least
4839  // one failed.
4840  }
4841 
4842  // BY THIS POINT, FOR THIS PARTY, we have successfully loaded and
4843  // verified ALL of the Nyms,
4844  // for ALL of the party's agents, and ALL of the asset accounts, for
4845  // this party. We know the
4846  // Party has pointers internally to all of those objects as well.
4847  // Therefore if we erase any of those objects, we must also clear the
4848  // pointers!
4849  //
4850  const bool bAreAcctsVerified = pParty->VerifyAccountsWithTheirAgents(
4851  theServerNym, strServerID,
4852  bBurnTransNo); // bBurnTransNo=false by default.
4853  if (!bAreAcctsVerified) {
4854  otOut << __FUNCTION__
4855  << ": Failed trying to Verify Asset Accts with their Agents, "
4856  "for party: " << str_party_name << "\n";
4857  bAreAnyInvalidAccounts = true; // We let them all go through, so
4858  // there is consistent output, but we
4859  // still take notice that at least
4860  // one failed.
4861  }
4862 
4863  // Now we don't delete these until AFTER the loop, until after we know
4864  // if it was a success.
4865  // If it failed, then we can fix their closing transaction numbers from
4866  // "used but still issued" back to
4867  // "issued and available for use." (If it was a success, then we don't
4868  // do anything, since the numbers are
4869  // already marked appropriately. And we still clean up all the nyms /
4870  // accounts--just AFTER this loop.)
4871  //
4872  // pParty->ClearTemporaryPointers(); // Don't want any bad
4873  // pointers floating around after cleanup. (Pointers must be cleared in
4874  // same scope as whatever they point to...)
4875  // OTSmartContract::CleanupNyms (map_Nyms_NewlyLoaded); // HAVE to
4876  // do this, or we'll leak. Even if something returned
4877  // OTSmartContract::CleanupAccts(map_Accts_NewlyLoaded); // false,
4878  // some objects may have been loaded before it failed.
4879  }
4880 
4881  const bool bSuccess = (!bAreAnyInvalidParties &&
4882  !bAreAnyInvalidAccounts); // <=== THE RETURN VALUE
4883 
4884  if (bAreAnyInvalidParties)
4885  otOut << __FUNCTION__ << ": Failure: There are invalid party(s) on "
4886  "this smart contract.\n";
4887 
4888  if (bAreAnyInvalidAccounts)
4889  otOut << __FUNCTION__ << ": Failure: there are invalid account(s) or "
4890  "authorized agent(s) on this smart "
4891  "contract.\n";
4892 
4893  // IF we marked the numbers as IN USE (bBurnTransNo) but then FAILURE
4894  // occurred,
4895  // then we need to CLOSE the opening numbers (RemoveIssuedNum) meaning they
4896  // are done
4897  // and over, and can never be used again, and we also need to HARVEST the
4898  // CLOSING
4899  // numbers, meaning they are available again for use in the future.
4900  // (If failure occurred in a case where we did NOT burn the numbers, then we
4901  // wouldn't
4902  // be worried about putting them back, now would we?)
4903  //
4904  //
4905  if (!bSuccess && // If this function was not a success, overall, and
4906  bBurnTransNo) // if we DID burn (mark as 'in use') the numbers during
4907  // this function...
4908  {
4909  // CloseoutOpeningNumbers...
4910  // This closes the opening numbers for all parties except the activator
4911  // Nym.
4912  // Why not him? Because his is already closed out in
4913  // NotarizeTransaction, if
4914  // the transaction has failed.
4915  //
4916  // Also, where that happens, his set of open cron items is also updated
4917  // to
4918  // remove the number from that list. (As the below function also does
4919  // for the rest
4920  // of the nyms involved.)
4921  //
4922  CloseoutOpeningNumbers(&theServerNym);
4923 
4924  // Then harvest those closing numbers back again (for ALL Nyms.)
4925  // (Not the opening numbers, which are already burned for good by this
4926  // point.)
4927  //
4929  &theServerNym, // theServerNym is the signer, here on the server
4930  // side.
4931  &theFailedParties); // Since we skipped marking the closing numbers
4932  // for these failed parties, then we skip adding
4933  // those same numbers back again, too.
4934  }
4935 
4936  // Now that all potentially-needed harvesting is done, we can clean up.
4937  //
4938  ClearTemporaryPointers(); // Don't want any bad pointers floating
4939  // around after cleanup.
4940 
4942  map_Nyms_Loaded_In_This_Function); // HAVE to do this, or we'll leak.
4943  // Even if something returned
4945  map_Accts_Loaded_In_This_Function); // false, some objects may have been
4946  // loaded before it failed.
4947 
4948  // DONE: if the above loop fails halfway through, then we should really PUT
4949  // BACK the closing
4950  // transaction #s that we removed. After all, we have a list of them.
4951  // Otherwise the only way
4952  // to know which parties have their numbers still, and which ones don't,
4953  // would be to stick a notice
4954  // in their nymbox, like we do for finalReceipt. Perhaps such a notice
4955  // should ALWAYS go into the
4956  // Nymbox in these cases... *shrug*
4957 
4958  return bSuccess;
4959 }
4960 
4961 // Used for closing-out the opening transaction numbers
4962 // (RemoveIssuedNum(lNymOpeningNumber)), for
4963 // all the Nyms, after the smart contract, for whatever reason, has failed to
4964 // activate. ASSUMES
4965 // the Nyms are already loaded, since this is used in a place where they are
4966 // already still loaded.
4967 // (Used above, in VerifySmartContract.)
4968 //
4969 // Also: Saves any Nyms that it does this for.
4970 // NOTE: Skips the activating Nym, since his opening number is ALREADY closed
4971 // out on failure,
4972 // in NotarizeTransaction.
4973 //
4974 // (Server-side.)
4975 //
4977 {
4978  const OTString strServerID(GetServerID());
4979 
4980  for (auto& it : m_mapParties) {
4981  OTParty* pParty = it.second;
4982  OT_ASSERT_MSG(nullptr != pParty,
4983  "OTSmartContract::CloseoutOpeningNumbers:"
4984  " Unexpected nullptr pointer in party map.");
4985 
4986  // Closeout the opening transaction numbers:
4987  //
4988  if (GetTransactionNum() !=
4989  pParty->GetOpeningTransNo()) // We skip the activating Nym. (His is
4990  // already closed-out in
4991  // NotarizeTransaction.)
4992  pParty->CloseoutOpeningNumber(strServerID, true, // bSave=true
4993  pSignerNym);
4994  }
4995 }
4996 
4997 // Used for adding the closing transaction numbers BACK to all the Nyms, after
4998 // the smart contract,
4999 // for whatever reason, has failed to activate. ASSUMES the Nyms are already
5000 // loaded, since this is
5001 // used in a place where they are already still loaded. (Used above, in
5002 // VerifySmartContract.)
5003 //
5004 // Also: Saves any Nyms that it harvests for.
5005 //
5006 // (Server-side.)
5007 //
5009  std::set<OTParty*>* pFailedParties)
5010 {
5011  const OTString strServerID(GetServerID());
5012 
5013  for (auto& it : m_mapParties) {
5014  const std::string str_party_name = it.first;
5015  OTParty* pParty = it.second;
5016  OT_ASSERT_MSG(nullptr != pParty,
5017  "OTSmartContract::HarvestClosingNumbers: "
5018  "Unexpected nullptr pointer in party map.");
5019 
5020  // If certain parties failed verification, then
5021  // OTSmartContract::VerifySmartContract() is smart enough
5022  // not to bother verifying the accounts of those parties. Thus, the
5023  // closing numbers for those accounts
5024  // could NOT have been marked as "used" (since they were skipped). So we
5025  // passed that same set of failed
5026  // parties into this function here, so that we can skip them here as
5027  // well, when harvesting the closing
5028  // numbers back again.
5029  //
5030  if (nullptr != pFailedParties) // There are failed parties.
5031  {
5032 
5033  // Skip failed parties...
5034  //
5035  auto it_failed = pFailedParties->find(pParty);
5036 
5037  if (pFailedParties->end() != it_failed) // this means pParty was
5038  // found on the FAILED list.
5039  // (So we can skip it here.)
5040  {
5041  otOut << __FUNCTION__ << ": FYI, at least one party ("
5042  << str_party_name
5043  << ") has failed verification, so right now I'm skipping "
5044  "harvesting of his "
5045  "closing transaction numbers. (Since he failed, we "
5046  "never verified his accounts, so we never grabbed "
5047  "those closing "
5048  "numbers in the first place, so there's no need to "
5049  "grab them back now.)\n";
5050  continue;
5051  }
5052  }
5053 
5054  // For all non-failed parties, now we harvest the closing transaction
5055  // numbers:
5056  //
5057  pParty->HarvestClosingNumbers(
5058  strServerID, // <============== (THE HARVEST.)
5059  true, // bSave=true
5060  pSignerNym);
5061  }
5062 }
5063 
5064 // Used for adding transaction numbers back to a Nym, after deciding not to use
5065 // this
5066 // smart contract, or failing in trying to use it.
5067 // Client side.
5068 //
5070 {
5071  // We do NOT call the parent version.
5072  // OTCronItem::HarvestClosingNumbers(theNym);
5073 
5074  // For payment plan, the parent (OTCronItem) grabs the sender's #s, and then
5075  // the subclass's
5076  // override (OTAgreement::HarvestClosingNumbers) grabs the recipient's #s.
5077  // But with SMART
5078  // CONTRACTS, there are only "the parties" and they ALL burned an opening #,
5079  // plus they can
5080  // ALL harvest their closing #s if activation failed. In fact, done: might
5081  // as well send them
5082  // all a notification if it fails, so they can all AUTOMATICALLY remove said
5083  // numbers from
5084  // their future balance agreements.
5085  //
5086 
5087  const OTString strServerID(GetServerID());
5088  const int32_t nTransNumCount = theNym.GetTransactionNumCount(
5089  GetServerID()); // save this to see if it changed, later.
5090 
5091  for (auto& it : m_mapParties) {
5092  OTParty* pParty = it.second;
5093  OT_ASSERT_MSG(nullptr != pParty,
5094  "Unexpected nullptr pointer in party map.");
5095 
5096  pParty->HarvestClosingNumbers(theNym, strServerID);
5097  }
5098 
5099  // It changed, so let's save it.
5100  if (nTransNumCount != theNym.GetTransactionNumCount(GetServerID()))
5101  theNym.SaveSignedNymfile(theNym);
5102 }
5103 
5104 // You usually wouldn't want to use this, since if the transaction failed, the
5105 // opening number
5106 // is already burned and gone. But there might be cases where it's not, and you
5107 // want to retrieve it.
5108 // So I added this function for those cases. (In most cases, you will prefer
5109 // HarvestClosingNumbers().)
5110 //
5111 // Client-side.
5112 //
5114 {
5115  // We do NOT call the parent version.
5116  // OTCronItem::HarvestOpeningNumber(theNym);
5117 
5118  // For payment plan, the parent (OTCronItem) grabs the sender's #s, and then
5119  // the subclass's
5120  // override (OTAgreement::HarvestClosingNumbers) grabs the recipient's #s.
5121  // But with SMART
5122  // CONTRACTS, there are only "the parties" and they ALL burned an opening #,
5123  // plus they can
5124  // ALL harvest their closing #s if activation failed. In fact, todo: might
5125  // as well send them
5126  // all a notification if it fails, so they can all AUTOMATICALLY remove said
5127  // numbers from
5128  // their future balance agreements.
5129  //
5130 
5131  const OTString strServerID(GetServerID());
5132  const int32_t nTransNumCount = theNym.GetTransactionNumCount(
5133  GetServerID()); // save this to see if it changed, later.
5134 
5135  for (auto& it : m_mapParties) {
5136  OTParty* pParty = it.second;
5137  OT_ASSERT_MSG(nullptr != pParty,
5138  "Unexpected nullptr pointer in party map.");
5139 
5140  pParty->HarvestOpeningNumber(theNym, strServerID);
5141  }
5142 
5143  // It changed, so let's save it.
5144  if (nTransNumCount != theNym.GetTransactionNumCount(GetServerID()))
5145  theNym.SaveSignedNymfile(theNym);
5146 }
5147 
5148 // static
5150 {
5151 
5152  while (!theMap.empty()) {
5153  OTPseudonym* pNym = theMap.begin()->second;
5154  OT_ASSERT(nullptr != pNym);
5155 
5156  delete pNym;
5157  pNym = nullptr;
5158 
5159  theMap.erase(theMap.begin());
5160  }
5161 }
5162 
5163 // static
5165 {
5166 
5167  while (!theMap.empty()) {
5168  OTAccount* pAcct = theMap.begin()->second;
5169  OT_ASSERT(nullptr != pAcct);
5170 
5171  delete pAcct;
5172  pAcct = nullptr;
5173 
5174  theMap.erase(theMap.begin());
5175  }
5176 }
5177 
5178 // AddParty()
5179 // For adding a theoretical party to a smart contract, as part of the contract's
5180 // design, so the
5181 // contract can be circulated BLANK and many different instances of it might be
5182 // used.
5183 //
5184 // (The party, at this stage, has a name, and accounts with asset types, but no
5185 // actual Nym IDs
5186 // or account IDs.)
5187 // This way any Nym or Entity could later sign on as the "trustee" or as the
5188 // "employee" etc. And
5189 // until they do, the contract still shows the "trustee" or "employee", allowing
5190 // the reader to see
5191 // how those entities are manipulated in the script code of the smartcontract.
5192 //
5194 {
5195  if (!theParty.HasActiveAgent()) {
5196  otOut << "OTSmartContract::AddParty: Party doesn't have an active "
5197  "agent -- who will sign for this smart contract?\n";
5198  return false;
5199  }
5200 
5201  // MIGHT move this below (1).. OR this might turn out to be important going
5202  // first...
5203  //
5204  if (!OTScriptable::AddParty(theParty)) {
5205  otOut << "OTSmartContract::AddParty: Failed adding party.\n";
5206  return false;
5207  }
5208 
5209  return true;
5210 }
5211 
5212 // Done:
5213 // Similar to AddParty(). Used afterwards.
5214 // ConfirmParty() looks up an existing party on the smart contract, then makes
5215 // sure that it matches
5216 // the one passed in, and then REPLACES the existing one with the new one that
5217 // was passed in. Unlike
5218 // AddParty (above) this version DOES expect account IDs, NymIDs, and
5219 // transaction numbers, and it DOES
5220 // save a signed copy internally as the ultimate confirmation. This version also
5221 // needs to validate
5222 // the signatures that are already there.
5223 // Client-side.
5224 //
5225 //
5226 // Note: AFTER A SUCCESSFUL CALL, the transaction numbers HAVE been set aside,
5227 // and must be retrieved
5228 // in the event of any failure.
5229 //
5231 {
5232  if (!theParty.HasActiveAgent()) {
5233  otOut << "OTSmartContract::ConfirmParty: Party doesn't have an active "
5234  "agent -- who will sign for this smart contract?\n";
5235  return false;
5236  }
5237 
5238  // Let's RESERVE however many transaction numbers we need to confirm this
5239  // smartcontract...
5240  //
5241  const OTString strServerID(GetServerID());
5242 
5243  // ReserveTransNumsForConfirm() sets aside the Opening # for the party,
5244  // as well as the Closing #s for all the asset accounts for that party.
5245  //
5246  // This MUST be done before calling OTScriptable::ConfirmParty, because
5247  // *this will get SIGNED in there, and so must have its final data in
5248  // place already. If the confirmation fails, we will harvest the numbers
5249  // back again.
5250  //
5251  if (!theParty.ReserveTransNumsForConfirm(strServerID)) {
5252  otOut << "OTSmartContract::ConfirmParty: Failure trying to reserve "
5253  "transaction numbers for "
5254  "the smart contract. (Nym needs more numbers than he has.)\n";
5255  return false;
5256  }
5257  // Note: BELOW THIS POINT, the transaction numbers have been set aside, and
5258  // must be retrieved,
5259  // below this point, in the event of any failure, using this call:
5260  // theParty.HarvestAllTransactionNumbers(strServerID);
5261 
5262  // Since EVERY party keeps his own signed copy, then we reset the creation
5263  // date
5264  // before EACH signature. That way, we have the date of signing for EVERY
5265  // signer.
5266  // (The final date will be set upon activation.)
5267  //
5268  const time64_t& CURRENT_TIME = OTTimeGetCurrentTime(),
5269  OLD_TIME = GetCreationDate();
5270 
5271  // Set the Creation Date.
5272  SetCreationDate(CURRENT_TIME);
5273 
5274  // THIS IS where the SIGNED COPY is SAVED, so all final changes must occur
5275  // ABOVE this point.
5276  //
5277  if (!OTScriptable::ConfirmParty(theParty)) {
5278  otOut << "OTSmartContract::ConfirmParty: Failed confirming party.\n";
5279  SetCreationDate(OLD_TIME); // Might as well set this back.
5280  theParty.HarvestAllTransactionNumbers(strServerID); // If it failed,
5281  // grab BACK the
5282  // numbers that we
5283  // reserved above.
5284  return false;
5285  }
5286 
5287  // SUCCESS!!
5288  //
5289  return true;
5290 
5291  // Are we good? The contract is compared against the other parties' signed
5292  // contracts; my own party and
5293  // transaction #s are added, and a signed copy of everything is saved in my
5294  // party. Then the entire contract
5295  // is re-signed (saving its updated contents) and then sent on to the next
5296  // party, who is free to release that
5297  // signature since I already have a signed copy in my party.
5298  //
5299  // Assuming all parties have signed AND provided valid transaction #s, then
5300  // the server is free to get started
5301  // immediately upon activation, and furthermore to cancel whenever it wants
5302  // (and probably just according to
5303  // the terms.) There should be a standard call for seeing if a person can
5304  // cancel the agreement, and if it's
5305  // not overridden in the contract, then it defaults to return true. (Note:
5306  // that is done now.)
5307  //
5308  // Technically ANY party's authorizing agent could become the originator by
5309  // activating the contract, but
5310  // only if all parties have validly signed. (Server needs to verify.)
5311 }
5312 
5313 // ALWAYS succeeds. (It will OT_ASSERT() otherwise.)
5314 //
5315 OTStash* OTSmartContract::GetStash(std::string str_stash_name)
5316 {
5317  auto it = m_mapStashes.find(str_stash_name);
5318 
5319  if (m_mapStashes.end() == it) // It's not there. Create it.
5320  {
5321  OTStash* pStash = new OTStash(str_stash_name);
5322  OT_ASSERT(nullptr != pStash);
5323 
5324  m_mapStashes.insert(
5325  std::pair<std::string, OTStash*>(str_stash_name, pStash));
5326  return pStash;
5327  }
5328 
5329  OTStash* pStash = it->second;
5330  OT_ASSERT(nullptr != pStash);
5331 
5332  return pStash;
5333 }
5334 
5336  : ot_super()
5337  , m_StashAccts(OTAccount::stash)
5338  , m_tNextProcessDate(OT_TIME_ZERO)
5339 {
5341 }
5342 
5344  : ot_super()
5345  , m_StashAccts(OTAccount::stash)
5346  , m_tNextProcessDate(OT_TIME_ZERO)
5347 {
5348  OTInstrument::SetServerID(SERVER_ID);
5350 }
5351 
5353 {
5355 }
5356 
5358 {
5359  m_strContractType = "SMARTCONTRACT";
5360 
5362  SMART_CONTRACT_PROCESS_INTERVAL); // Smart contracts current default is
5363  // 30 seconds. Actual default will
5364  // probably be configurable in config
5365  // file, and most contracts will also
5366  // probably override this.
5367 }
5368 
5370 {
5371 
5372  while (!m_mapStashes.empty()) {
5373  OTStash* pStash = m_mapStashes.begin()->second;
5374  OT_ASSERT(nullptr != pStash);
5375 
5376  delete pStash;
5377  pStash = nullptr;
5378 
5379  m_mapStashes.erase(m_mapStashes.begin());
5380  }
5381 
5382  m_StashAccts.Release();
5383 }
5384 
5386 {
5387 
5388  ReleaseStashes();
5389 }
5390 
5392 {
5394 
5395  ot_super::Release(); // since I've overridden the base class, I call it
5396  // now...
5397 
5398  // Then I call this to re-initialize everything
5400 }
5401 
5403 {
5404  return static_cast<int32_t>(m_mapStashes.size());
5405 }
5406 
5408 {
5409  return m_StashAccts.GetCountAccountIDs();
5410 }
5411 
5412 // Done.
5413 //
5414 // Before we can make sure that ALL parties have signed equivalent versions,
5415 // we must be able to compare TWO versions. The below function does that.
5416 //
5418 {
5419  if (!OTScriptable::Compare(rhs)) return false;
5420 
5421  if (GetCountStashes() > 0) {
5422  otErr << "OTSmartContract::Compare: Error: How is this function EVER "
5423  "being called when there are stashes present? Only the server "
5424  "can create stashes.\n";
5425  return false;
5426  }
5427 
5428  if (GetCountStashAccts() > 0) {
5429  otErr << "OTSmartContract::Compare: Error: How is this function EVER "
5430  "being called when there are "
5431  "stash accounts present? Only the server can create stash "
5432  "accounts.\n";
5433  return false;
5434  }
5435 
5436  // Compare OTSmartContract specific info here.
5437  const OTSmartContract* pSmartContract =
5438  dynamic_cast<const OTSmartContract*>(&rhs);
5439 
5440  if (nullptr != pSmartContract) {
5441  if (pSmartContract->GetCountStashes() > 0) {
5442  otErr << "OTSmartContract::Compare: Error: How is this function "
5443  "EVER being called when there are stashes present on rhs? "
5444  "Only the server can create stashes.\n";
5445  return false;
5446  }
5447 
5448  if (pSmartContract->GetCountStashAccts() > 0) {
5449  otErr << "OTSmartContract::Compare: Error: How is this function "
5450  "EVER being called when there are stash accounts present "
5451  "on rhs? Only the server can create stash accounts.\n";
5452  return false;
5453  }
5454 
5455  if ((GetServerID() == pSmartContract->GetServerID()) &&
5456  (GetValidFrom() == pSmartContract->GetValidFrom()) &&
5457  (GetValidTo() == pSmartContract->GetValidTo()))
5458  return true;
5459  }
5460 
5461  return false;
5462 }
5463 
5465 {
5466  // I release this because I'm about to repopulate it.
5468 
5469  const OTString SERVER_ID(GetServerID()),
5470  ACTIVATOR_USER_ID(GetSenderUserID()),
5471  ACTIVATOR_ACCT_ID(GetSenderAcctID());
5472 
5473  OT_ASSERT(nullptr != m_pCancelerNymID);
5474 
5475  OTString strCanceler;
5476 
5477  if (m_bCanceled) m_pCancelerNymID->GetString(strCanceler);
5478 
5479  int64_t tCreation = OTTimeGetSecondsFromTime(
5481  int64_t tValidFrom = OTTimeGetSecondsFromTime(
5483  int64_t tValidTo = OTTimeGetSecondsFromTime(
5485  int64_t tNextProcess = OTTimeGetSecondsFromTime(
5487 
5488  // OTSmartContract
5490  "<smartContract\n version=\"%s\"\n"
5491  " serverID=\"%s\"\n"
5492  " activatorUserID=\"%s\"\n"
5493  " activatorAcctID=\"%s\"\n"
5494  " lastSenderUserID=\"%s\"\n"
5495  " lastSenderAcctID=\"%s\"\n"
5496  " lastRecipientUserID=\"%s\"\n"
5497  " lastRecipientAcctID=\"%s\"\n"
5498  " canceled=\"%s\"\n"
5499  " cancelerUserID=\"%s\"\n"
5500  " transactionNum=\"%lld\"\n"
5501  " creationDate=\"%" PRId64 "\"\n"
5502  " validFrom=\"%" PRId64 "\"\n"
5503  " validTo=\"%" PRId64 "\"\n"
5504  " nextProcessDate=\"%" PRId64 "\""
5505  " >\n\n",
5506  m_strVersion.Get(), m_bCalculatingID ? "" : SERVER_ID.Get(),
5507  m_bCalculatingID ? "" : ACTIVATOR_USER_ID.Get(),
5508  m_bCalculatingID ? "" : ACTIVATOR_ACCT_ID.Get(),
5509  m_bCalculatingID ? "" : m_strLastSenderUser.Get(),
5510  m_bCalculatingID ? "" : m_strLastSenderAcct.Get(),
5511  m_bCalculatingID ? "" : m_strLastRecipientUser.Get(),
5512  m_bCalculatingID ? "" : m_strLastRecipientAcct.Get(),
5513  m_bCanceled ? "true" : "false", m_bCanceled ? strCanceler.Get() : "",
5514  m_bCalculatingID ? 0 : m_lTransactionNum, tCreation, tValidFrom,
5515  tValidTo, tNextProcess);
5516 
5517  // OTCronItem
5518  if (!m_bCalculatingID) {
5519  for (int32_t i = 0; i < GetCountClosingNumbers(); i++) {
5520  int64_t lClosingNumber = GetClosingTransactionNoAt(i);
5521  OT_ASSERT(lClosingNumber > 0);
5522 
5524  "<closingTransactionNumber value=\"%lld\"/>\n\n",
5525  lClosingNumber);
5526 
5527  // For OTSmartContract, this should only contain a single number,
5528  // from the activator Nym.
5529  // I preserved the loop anyway. Call me crazy. But I'm still
5530  // displaying an error if there's
5531  // more than one.
5532  if (i > 0)
5533  otErr << "OTSmartContract::" << __FUNCTION__
5534  << ": ERROR: There's only ever "
5535  "supposed to be a single closing number here (for "
5536  "smart contracts.)\n";
5537  }
5538  }
5539 
5540  // *** OT SCRIPTABLE ***
5541  //
5543  m_bCalculatingID); // FYI: this is: void
5544 
5545  if (!m_bCalculatingID) {
5546 
5547  // Save m_StashAccts.
5548  //
5549  // (This is an object that contains a map of OTAccountIDs, by
5550  // asset_type_id)
5551  //
5552  m_StashAccts.Serialize(m_xmlUnsigned);
5553 
5554  // This is a map of OTStash's, by stash_name.
5555  // EACH ONE contains a map of OTStashItems, by asset_type_id
5556 
5557  // These stashes are what the scripts interact with. They have names.
5558  // Whereas the stash accts (above) are the actual accountIDs
5559  for (auto& it : m_mapStashes) {
5560  // where the actual funds are stored for each asset type.
5561  OTStash* pStash = it.second;
5562  OT_ASSERT(nullptr != pStash);
5563  pStash->Serialize(m_xmlUnsigned);
5564  }
5565  }
5566 
5567  m_xmlUnsigned.Concatenate("</smartContract>\n\n");
5568 }
5569 
5570 // Used internally here.
5572 {
5573  m_strLastSenderUser.Release(); // This is the last User ID of a party who
5574  // SENT money.
5575  m_strLastSenderAcct.Release(); // This is the last Acct ID of a party who
5576  // SENT money.
5577  m_strLastRecipientUser.Release(); // This is the last User ID of a party who
5578  // RECEIVED money.
5579  m_strLastRecipientAcct.Release(); // This is the last Acct ID of a party who
5580  // RECEIVED money.
5581 }
5582 
5583 // We call this just before activation (in OT_API::activateSmartContract) in
5584 // order
5585 // to make sure that certain IDs and transaction #s are set, so the smart
5586 // contract
5587 // will interoperate with the old Cron Item system of doing things.
5588 //
5589 void OTSmartContract::PrepareToActivate(const int64_t& lOpeningTransNo,
5590  const int64_t& lClosingTransNo,
5591  const OTIdentifier& theUserID,
5592  const OTIdentifier& theAcctID)
5593 {
5594  SetTransactionNum(lOpeningTransNo);
5595 
5596  ClearClosingNumbers(); // Just in case. Should be unnecessary, but you never
5597  // know how people might screw around.
5598  AddClosingTransactionNo(lClosingTransNo);
5599 
5600  SetSenderUserID(theUserID); // This is the activator of the contract. (NOT
5601  // the actual "sender" of any single payment, in
5602  // the case of smart contracts anyway.)
5603  SetSenderAcctID(theAcctID); // This is an account provided by the activator
5604  // so a closing number and final receipt are
5605  // guaranteed for this smart contract.
5606 
5607  ReleaseLastSenderRecipientIDs(); // These should be blank starting out
5608  // anyway.
5609 
5610  // You shouldn't have any of these anyway; the server only creates
5611  // them after a smart contract is activated.
5612  //
5613  ReleaseStashes();
5614 }
5615 
5616 // return -1 if error, 0 if nothing, and 1 if the node was processed.
5618 {
5619  const OTString strNodeName(xml->getNodeName());
5620 
5621  int32_t nReturnVal = 0;
5622 
5623  // Here we call the parent class first.
5624  // If the node is found there, or there is some error,
5625  // then we just return either way. But if it comes back
5626  // as '0', then nothing happened, and we'll continue executing.
5627  //
5628  // OTSmartContract::ProcessXMLNode calls OTCronItem::ProcessXMLNode,
5629  // which calls OTScriptable... Meaning:
5630  //
5631  // NO NEED to explicitly load OTScriptable stuff here!
5632  //
5633  nReturnVal = ot_super::ProcessXMLNode(xml);
5634 
5635  if (0 != (nReturnVal)) {
5636  return nReturnVal;
5637  }
5638 
5639  if (strNodeName.Compare("smartContract")) {
5640  m_strVersion = xml->getAttributeValue("version");
5641 
5642  const OTString strServerID(xml->getAttributeValue("serverID"));
5643  const OTString strActivatorUserID(
5644  xml->getAttributeValue("activatorUserID"));
5645  const OTString strActivatorAcctID(
5646  xml->getAttributeValue("activatorAcctID"));
5647  const OTString strCanceled(xml->getAttributeValue("canceled"));
5648  const OTString strCancelerUserID(
5649  xml->getAttributeValue("cancelerUserID"));
5650 
5651  if (strServerID.Exists()) {
5652  const OTIdentifier SERVER_ID(strServerID);
5653  SetServerID(SERVER_ID);
5654  }
5655  if (strActivatorUserID.Exists()) {
5656  const OTIdentifier ACTIVATOR_USER_ID(strActivatorUserID);
5657  SetSenderUserID(ACTIVATOR_USER_ID);
5658  }
5659  if (strActivatorAcctID.Exists()) {
5660  const OTIdentifier ACTIVATOR_ACCT_ID(strActivatorAcctID);
5661  SetSenderAcctID(ACTIVATOR_ACCT_ID);
5662  }
5663 
5664  if (strCanceled.Exists() && strCanceled.Compare("true")) {
5665  m_bCanceled = true;
5666 
5667  if (strCancelerUserID.Exists())
5668  m_pCancelerNymID->SetString(strCancelerUserID);
5669  // else log
5670  }
5671  else {
5672  m_bCanceled = false;
5674  }
5675 
5676  const OTString strTransNum = xml->getAttributeValue("transactionNum");
5677 
5678  SetTransactionNum(strTransNum.Exists() ? atol(strTransNum.Get()) : 0);
5679 
5680  const OTString str_valid_from = xml->getAttributeValue("validFrom");
5681  const OTString str_valid_to = xml->getAttributeValue("validTo");
5682  const OTString str_creation = xml->getAttributeValue("creationDate");
5683  const OTString str_next_process =
5684  xml->getAttributeValue("nextProcessDate");
5685 
5686  int64_t tValidFrom = str_valid_from.ToLong();
5687  int64_t tValidTo = str_valid_to.ToLong();
5688  int64_t tCreation = str_creation.ToLong();
5689  int64_t tNextProcess = str_next_process.ToLong();
5690 
5695 
5696  // These are stored for RECEIPTS, so if there is an inbox receipt with
5697  // an amount,
5698  // we will know who was sending and receiving. If sender or receiver is
5699  // blank, that
5700  // means the source/destination was a STASH instead of an account. FYI.
5701  //
5702  m_strLastSenderUser = xml->getAttributeValue(
5703  "lastSenderUserID"); // Last User ID of a party who SENT money.
5704  m_strLastSenderAcct = xml->getAttributeValue(
5705  "lastSenderAcctID"); // Last Acct ID of a party who SENT money.
5706  m_strLastRecipientUser =
5707  xml->getAttributeValue("lastRecipientUserID"); // Last User ID of a
5708  // party who RECEIVED
5709  // money.
5710  m_strLastRecipientAcct =
5711  xml->getAttributeValue("lastRecipientAcctID"); // Last Acct ID of a
5712  // party who RECEIVED
5713  // money.
5714 
5715  otWarn << "\n\n Smartcontract. Transaction Number: "
5716  << m_lTransactionNum << "\n";
5717 
5718  otInfo << " Creation Date: " << tCreation
5719  << " Valid From: " << tValidFrom << "\n Valid To: " << tValidTo
5720  << "\n"
5721  " ServerID: " << strServerID
5722  << "\n"
5723  " activatorUserID: " << strActivatorUserID << "\n ";
5724 
5725  nReturnVal = 1;
5726  }
5727  else if (strNodeName.Compare("accountList")) // the stash reserve account
5728  // IDs.
5729  {
5730  const OTString strAcctType = xml->getAttributeValue("type");
5731  const OTString strAcctCount = xml->getAttributeValue("count");
5732 
5733  if ((-1) ==
5734  m_StashAccts.ReadFromXMLNode(xml, strAcctType, strAcctCount)) {
5735  otErr << "OTSmartContract::ProcessXMLNode: Error loading stash "
5736  "accountList.\n";
5737  nReturnVal = (-1);
5738  }
5739  else
5740  nReturnVal = 1;
5741  }
5742  else if (strNodeName.Compare("stash")) // the actual stashes.
5743  {
5744  const OTString strStashName = xml->getAttributeValue("name");
5745  const OTString strItemCount = xml->getAttributeValue("count");
5746 
5747  const std::string str_stash_name = strStashName.Get();
5748  OTStash* pStash = new OTStash(str_stash_name);
5749  OT_ASSERT(nullptr != pStash);
5750 
5751  if ((-1) == pStash->ReadFromXMLNode(xml, strStashName, strItemCount)) {
5752  otErr << "OTSmartContract::ProcessXMLNode: Error loading stash: "
5753  << strStashName << "\n";
5754  delete pStash;
5755  nReturnVal = (-1);
5756  }
5757  else {
5758  // Success
5759  //
5760  m_mapStashes.insert(
5761  std::pair<std::string, OTStash*>(strStashName.Get(), pStash));
5762 
5763  nReturnVal = 1;
5764  }
5765  }
5766 
5767  return nReturnVal;
5768 }
5769 
5770 bool OTSmartContract::SaveContractWallet(std::ofstream&) const
5771 {
5772  return true;
5773 }
5774 
5775 // DONE: Make a GENERIC VERSION of the BELOW function, that script coders can
5776 // call
5777 // whenever they need to move money between two parties!!!! The more I look at
5778 // it,
5779 // the more I realize I can probably use it NEARLY "as is" !
5780 //
5781 // true == success, false == failure.
5782 //
5783 bool OTSmartContract::MoveFunds(
5784  const mapOfNyms& map_NymsAlreadyLoaded, const int64_t& lAmount,
5785  const OTIdentifier& SOURCE_ACCT_ID, // GetSenderAcctID();
5786  const OTIdentifier& SENDER_USER_ID, // GetSenderUserID();
5787  const OTIdentifier& RECIPIENT_ACCT_ID, // GetRecipientAcctID();
5788  const OTIdentifier& RECIPIENT_USER_ID) // GetRecipientUserID();
5789 {
5790  OTCron* pCron = GetCron();
5791  OT_ASSERT(nullptr != pCron);
5792 
5793  OTPseudonym* pServerNym = pCron->GetServerNym();
5794  OT_ASSERT(nullptr != pServerNym);
5795 
5796  if (lAmount <= 0) {
5797  otOut << " OTCronItem::MoveFunds: Error: lAmount cannot be 0 or <0. "
5798  "(Value passed in was " << lAmount << ".)\n";
5799  return false;
5800  }
5801 
5802  bool bSuccess = false; // The return value.
5803 
5804  const OTIdentifier SERVER_ID(pCron->GetServerID());
5805  const OTIdentifier SERVER_USER_ID(*pServerNym);
5806 
5807  OTString strSenderUserID(SENDER_USER_ID),
5808  strRecipientUserID(RECIPIENT_USER_ID), strSourceAcctID(SOURCE_ACCT_ID),
5809  strRecipientAcctID(RECIPIENT_ACCT_ID), strServerNymID(SERVER_USER_ID);
5810 
5811  // Make sure they're not the same Account IDs ...
5812  // Otherwise we would have to take care not to load them twice, like with
5813  // the Nyms below.
5814  // (Instead I just disallow it entirely. After all, even if I DID allow the
5815  // account to transfer
5816  // to itself, there would be no difference in balance than disallowing it.)
5817  //
5818  if (SOURCE_ACCT_ID == RECIPIENT_ACCT_ID) {
5819  otOut << "OTCronItem::MoveFunds: Aborted move: both account IDs were "
5820  "identical.\n";
5821  FlagForRemoval(); // Remove from Cron
5822  return false; // TODO: should have a "Validate Scripts" function that
5823  // weeds this crap out before we even get here. (There are
5824  // other examples...)
5825  }
5826  // When the accounts are actually loaded up, then we should also compare
5827  // the asset types to make sure they were what we expected them to be.
5828 
5829  // Need to load up the ORIGINAL VERSION OF THIS SMART CONTRACT
5830  // Will need to verify the parties' signatures, as well as attach a copy of
5831  // it to the receipt.
5832 
5833  OTCronItem* pOrigCronItem = nullptr;
5834 
5835  // OTCronItem::LoadCronReceipt loads the original version with the user's
5836  // signature.
5837  // (Updated versions, as processing occurs, are signed by the server.)
5839 
5840  OT_ASSERT(nullptr != pOrigCronItem); // How am I processing it now if the
5841  // receipt wasn't saved in the first
5842  // place??
5843  // TODO: Decide global policy for handling situations where the hard drive
5844  // stops working, etc.
5845 
5846  // When theOrigPlanGuardian goes out of scope, pOrigCronItem gets deleted
5847  // automatically.
5848  std::unique_ptr<OTCronItem> theOrigPlanGuardian(pOrigCronItem);
5849 
5850  // strOrigPlan is a String copy (a PGP-signed XML file, in string form) of
5851  // the original Payment Plan request...
5852  OTString strOrigPlan(*pOrigCronItem); // <====== Farther down in the code, I
5853  // attach this string to the receipts.
5854 
5855  // Make sure to clean these up.
5856  // delete pOrigCronItem; // theOrigPlanGuardian will handle this
5857  // now, whenever it goes out of scope.
5858  // pOrigCronItem = nullptr; // So I don't need to worry about
5859  // deleting this anymore. I can keep it around and
5860  // use it all I want, and return anytime, and it won't leak.
5861 
5862  // -------------- Make sure have both nyms loaded and checked out.
5863  // --------------------------------------------------
5864  // WARNING: 1 or both of the Nyms could be also the Server Nym. They could
5865  // also be the same Nym, but NOT the Server.
5866  // In all of those different cases, I don't want to load the same file twice
5867  // and overwrite it with itself, losing
5868  // half of all my changes. I have to check all three IDs carefully and set
5869  // the pointers accordingly, and then operate
5870  // using the pointers from there.
5871 
5872  OTPseudonym theSenderNym, theRecipientNym; // We MIGHT use ONE, OR BOTH, of
5873  // these, or none. (But probably
5874  // both.)
5875 
5876  // Find out if either Nym is actually also the server.
5877  bool bSenderNymIsServerNym =
5878  ((SENDER_USER_ID == SERVER_USER_ID) ? true : false);
5879  bool bRecipientNymIsServerNym =
5880  ((RECIPIENT_USER_ID == SERVER_USER_ID) ? true : false);
5881 
5882  // We also see, after all that is done, whether both pointers go to the same
5883  // entity.
5884  // (We'll want to know that later.)
5885  bool bUsersAreSameNym =
5886  ((SENDER_USER_ID == RECIPIENT_USER_ID) ? true : false);
5887 
5888  OTPseudonym* pSenderNym = nullptr;
5889  OTPseudonym* pRecipientNym = nullptr;
5890 
5891  auto it_sender = map_NymsAlreadyLoaded.find(strSenderUserID.Get());
5892  auto it_recipient = map_NymsAlreadyLoaded.find(strRecipientUserID.Get());
5893 
5894  if (map_NymsAlreadyLoaded.end() !=
5895  it_sender) // found the sender in list of Nyms that are already loaded.
5896  {
5897  pSenderNym = it_sender->second;
5898  OT_ASSERT((nullptr != pSenderNym) &&
5899  (pSenderNym->CompareID(SENDER_USER_ID)));
5900  }
5901  if (map_NymsAlreadyLoaded.end() != it_recipient) // found the recipient in
5902  // list of Nyms that are
5903  // already loaded.
5904  {
5905  pRecipientNym = it_recipient->second;
5906  OT_ASSERT((nullptr != pRecipientNym) &&
5907  (pRecipientNym->CompareID(RECIPIENT_USER_ID)));
5908  }
5909 
5910  // Figure out if Sender Nym is also Server Nym.
5911  if (bSenderNymIsServerNym) {
5912  // If the First Nym is the server, then just point to that.
5913  pSenderNym = pServerNym;
5914  }
5915  else if (nullptr ==
5916  pSenderNym) // Else load the First Nym from storage, if
5917  // still not found.
5918  {
5919  theSenderNym.SetIdentifier(
5920  SENDER_USER_ID); // theSenderNym is pSenderNym
5921 
5922  if (!theSenderNym.LoadPublicKey()) {
5923  OTString strNymID(SENDER_USER_ID);
5924  otErr << "OTCronItem::MoveFunds: Failure loading Sender Nym public "
5925  "key: " << strNymID << "\n";
5926  FlagForRemoval(); // Remove it from future Cron processing, please.
5927  return false;
5928  }
5929 
5930  if (theSenderNym.VerifyPseudonym() &&
5931  theSenderNym.LoadSignedNymfile(*pServerNym)) // ServerNym here is
5932  // not theSenderNym's
5933  // identity, but merely
5934  // the signer on this
5935  // file.
5936  {
5937  otOut << "OTCronItem::MoveFunds: Loading sender Nym, since he **** "
5938  "APPARENTLY **** wasn't already loaded.\n"
5939  "(On a cron item processing, this is normal. But if you "
5940  "triggered a clause directly, then your Nym SHOULD be "
5941  "already loaded...)\n";
5942  pSenderNym = &theSenderNym; // <=====
5943  }
5944  else {
5945  OTString strNymID(SENDER_USER_ID);
5946  otErr << "OTCronItem::MoveFunds: Failure loading or verifying "
5947  "Sender Nym public key: " << strNymID << "\n";
5948  FlagForRemoval(); // Remove it from future Cron processing, please.
5949  return false;
5950  }
5951  }
5952 
5953  // Next, we also find out if Recipient Nym is Server Nym...
5954  if (bRecipientNymIsServerNym) {
5955  // If the Recipient Nym is the server, then just point to that.
5956  pRecipientNym = pServerNym;
5957  }
5958  else if (bUsersAreSameNym) // Else if the participants are the same Nym,
5959  // point to the one we already loaded.
5960  {
5961  pRecipientNym = pSenderNym; // theSenderNym is pSenderNym
5962  }
5963  else if (nullptr ==
5964  pRecipientNym) // Otherwise load the Other Nym from Disk
5965  // and point to that, if still not found.
5966  {
5967  theRecipientNym.SetIdentifier(RECIPIENT_USER_ID);
5968 
5969  if (!theRecipientNym.LoadPublicKey()) {
5970  OTString strNymID(RECIPIENT_USER_ID);
5971  otErr << "OTCronItem::MoveFunds: Failure loading Recipient Nym "
5972  "public key: " << strNymID << "\n";
5973  FlagForRemoval(); // Remove it from future Cron processing, please.
5974  return false;
5975  }
5976 
5977  if (theRecipientNym.VerifyPseudonym() &&
5978  theRecipientNym.LoadSignedNymfile(*pServerNym)) {
5979  otOut << "OTCronItem::MoveFunds: Loading recipient Nym, since he "
5980  "**** APPARENTLY **** wasn't already loaded.\n"
5981  "(On a cron item processing, this is normal. But if you "
5982  "triggered a clause directly, then your Nym SHOULD be "
5983  "already loaded...)\n";
5984 
5985  pRecipientNym = &theRecipientNym; // <=====
5986  }
5987  else {
5988  OTString strNymID(RECIPIENT_USER_ID);
5989  otErr << "OTCronItem::MoveFunds: Failure loading or verifying "
5990  "Recipient Nym public key: " << strNymID << "\n";
5991  FlagForRemoval(); // Remove it from future Cron processing, please.
5992  return false;
5993  }
5994  }
5995 
5996  // Below this point, both Nyms are loaded and good-to-go.
5997 
5998  mapOfNyms map_ALREADY_LOADED; // I know I passed in one of these, but now I
5999  // have processed the Nym pointers (above) and
6000  // have better data here now.
6001  auto it_temp = map_ALREADY_LOADED.find(strServerNymID.Get());
6002  if (map_ALREADY_LOADED.end() == it_temp)
6003  map_ALREADY_LOADED.insert(std::pair<std::string, OTPseudonym*>(
6004  strServerNymID.Get(),
6005  pServerNym)); // Add Server Nym to list of Nyms already loaded.
6006  it_temp = map_ALREADY_LOADED.find(strSenderUserID.Get());
6007  if (map_ALREADY_LOADED.end() == it_temp)
6008  map_ALREADY_LOADED.insert(std::pair<std::string, OTPseudonym*>(
6009  strSenderUserID.Get(),
6010  pSenderNym)); // Add Sender Nym to list of Nyms already loaded.
6011  it_temp = map_ALREADY_LOADED.find(strRecipientUserID.Get());
6012  if (map_ALREADY_LOADED.end() == it_temp)
6013  map_ALREADY_LOADED.insert(std::pair<std::string, OTPseudonym*>(
6014  strRecipientUserID.Get(), pRecipientNym)); // Add Recipient Nym to
6015  // list of Nyms already
6016  // loaded.
6017  //
6018  // I set up map_ALREADY_LOADED here so that when I call
6019  // VerifyAgentAsNym(), I can pass it along. VerifyAgentAsNym often
6020  // just verifies ownership (for individual nym owners who act as their own
6021  // agents.) BUT... If we're in a smart contract,
6022  // or other OTScriptable, there might be a party owned by an entity, and a
6023  // signature needs to be checked that ISN'T the
6024  // same Nym! (Perhaps the entity signed the smartcontract via another
6025  // signer Nym.) This means I might potentially have to
6026  // LOAD the other signer Nym, in order to verify his signature...BUT WHAT
6027  // IF HE'S ALREADY LOADED?
6028  //
6029  // THAT... is exactly why I am passing in a list now of all the Nyms that
6030  // are already loaded... So if the authorizing Nym for
6031  // any given party happens to already be loaded on that list, it can use
6032  // it, instead of loading it twice (and potentially
6033  // overwriting data... Bad thing!)
6034  //
6035  // Now that I have the original cron item loaded, and all the Nyms ready to
6036  // go,
6037  // let's make sure that BOTH the nyms in question have SIGNED the original
6038  // request.
6039  // (Their signatures wouldn't be on the updated version in Cron--the server
6040  // signs
6041  // that one. Except smart contracts, which keep a signed copy automatically
6042  // for each party.)
6043  //
6044  // NOTE: originally I used to just verify here that both Nyms have signed
6045  // the original
6046  // cron item. But now I provide a virtual method to do that (which it still
6047  // does, by default.)
6048  // But in the case of smart contracts, it's more complicated. The Nym might
6049  // merely be an agent
6050  // for a party, (legitimately) but where a DIFFERENT agent is the one who
6051  // originally signed.
6052  // Thus, I have to allow SmartContract to override the method so it can add
6053  // that extra intelligence.
6054  //
6055  // NOTE: This function does NOT verify that the Nyms are authorized for the
6056  // ASSET ACCOUNTS--either the
6057  // party providing authorization OR the acct itself. Instead, this ONLY
6058  // verifies that they are actually
6059  // agents for legitimate parties to this agreement ACCORDING TO THOSE
6060  // PARTIES, (regardless of the asset
6061  // accounts) and that said agreement has also been signed by authorized
6062  // agents of those parties.
6063  // (Usually the agent who originally signed, and the agent signing now, and
6064  // the
6065  // party that agent represents, are all in reality the SAME NYM. But in the
6066  // case of
6067  // smart contracts, they can be different Nyms, which is why we now have an
6068  // overridable virtual method
6069  // for this, instead of simply verifying both signatures on the cron item
6070  // itself, as the default
6071  // OTTrade and OTAgreement versions of that virtual method will continue to
6072  // do.
6073  //
6074  // Repeat: this is not about verifying account ownershp or permissions. It's
6075  // ONLY about verifying
6076  // that these nyms are actually authorized to act as parties to the
6077  // agreement. Verifying their ownership
6078  // rights over the asset accounts is done separately below.
6079  //
6080  // Another thing: The original "VerifySignature()" proved that the NYM
6081  // HIMSELF had signed/authorized,
6082  // whereas now it's more like, prove which party owns the account, then
6083  // prove that party has authorized
6084  // Nym as his agent.
6085  //
6086 
6087  // VerifyNymAsAgent() replaces VerifySignature() here. It's polymorphic, so
6088  // VerifySignature() is still called
6089  // directly on theNym in certain versions (agreement, trade...) but
6090  // otherwise there is now more to it than that.
6091  // See OTScriptable for the complicated version. Either way, it makes sure
6092  // that the right person signed and that
6093  // theNym is authorized to act by that person. (As far as pOrigCronItem
6094  // cares -- the Account may still disagree.)
6095  // This verifies:
6096  // - that the Nym is found as an agent on one of the parties.
6097  // - that there is an "original party signed copy" of the contract attached
6098  // to the party.
6099  // - that there is an authorizing agent for that party whose SIGNATURE
6100  // VERIFIES on the party's signed copy.
6101  //
6102  if (!pOrigCronItem->VerifyNymAsAgent(
6103  *pSenderNym, *pServerNym,
6104  // In case it needs to load the AUTHORIZING agent, and that agent
6105  // is already loaded, it will have access here.
6106  &map_ALREADY_LOADED)) {
6107  otErr << "OTCronItem::MoveFunds: Failed authorization for sender Nym: "
6108  << strSenderUserID << "\n";
6109  FlagForRemoval(); // Remove it from Cron.
6110  return false;
6111  }
6112 
6113  if (!pOrigCronItem->VerifyNymAsAgent(
6114  *pRecipientNym, *pServerNym,
6115  // In case it needs to load the AUTHORIZING agent, and that agent
6116  // is already loaded, it will have access here.
6117  &map_ALREADY_LOADED)) {
6118  otErr
6119  << "OTCronItem::MoveFunds: Failed authorization for recipient Nym: "
6120  << strRecipientUserID << "\n";
6121  FlagForRemoval(); // Remove it from Cron.
6122  return false;
6123  }
6124 
6125  // (verifications)
6126  //
6127  // -- DONE Verify that both Nyms are actually authorized to act as agents
6128  // for the parties. (in the cron item.) This is like
6129  // pOrig->VerifySignature(theNym);
6130  // -- DONE Verify that both parties have properly signed/executed the
6131  // contract. This may mean loading a DIFFERENT Nym (the authorizing agent
6132  // who signed for the party originally)
6133  // This is also like pOrig->VerifySignature(theNym); the extra
6134  // functionality is added via polymorphism.
6135  // -- DONE Verify that both Nyms are authorized agents FOR THE ASSET
6136  // ACCOUNTS IN QUESTION, according to their PARTIES. This is like
6137  // pParty->HasAgent(theNym);
6138  // -- DONE Verify that both ACCOUNTS are owned by the parties that the Nyms
6139  // represent. According to the ACCOUNTS. This is like
6140  // pAcct->VerifyOwner(theNym)
6141  // The above two items should ALSO be done polymorphically, just like the
6142  // first two.
6143  // -- If the Nyms are not the parties they represent, then verify that they
6144  // have the proper Role at their entities in order to claim such authority.
6145  // Does this last one go into OTAccount itself? Or OTScriptable. And the
6146  // actual verification part will be probably in OTAgent, just like
6147  // VerifySignature was.
6148  //
6149  // if (!pOrigCronItem->VerifySignature(*pSenderNym) ||
6150  // !pOrigCronItem->VerifySignature(*pRecipientNym))
6151  //
6152  // {
6153  // otErr << "OTCronItem::MoveFunds: Failed authorization.\n";
6154  // FlagForRemoval(); // Remove it from Cron.
6155  // return false;
6156  // }
6157 
6158  // AT THIS POINT, I have pServerNym, pSenderNym, and pRecipientNym.
6159  // ALL are loaded from disk (where necessary.) AND...
6160  // ALL are valid pointers, (even if they sometimes point to the same
6161  // object,)
6162  // AND none are capable of overwriting the storage of the other (by
6163  // accidentally
6164  // loading the same storage twice.)
6165  // We also have boolean variables at this point to tell us exactly which are
6166  // which,
6167  // (in case some of those pointers do go to the same object.)
6168  // They are:
6169  // bSenderNymIsServerNym, bRecipientNymIsServerNym, and bUsersAreSameNym.
6170  //
6171  // I also have pOrigCronItem, which is a dynamically-allocated copy of the
6172  // original
6173  // Cron Receipt for this Cron Item. (And I don't need to worry about
6174  // deleting it, either.)
6175  // I know for a fact they are both authorized on pOrigCronItem...
6176 
6177  // LOAD THE ACCOUNTS
6178  //
6179  OTAccount* pSourceAcct =
6180  OTAccount::LoadExistingAccount(SOURCE_ACCT_ID, SERVER_ID);
6181 
6182  if (nullptr == pSourceAcct) {
6183  otOut << "OTCronItem::MoveFunds: ERROR verifying existence of source "
6184  "account.\n";
6185  FlagForRemoval(); // Remove it from future Cron processing, please.
6186  return false;
6187  }
6188  // Past this point we know pSourceAcct is good and will clean itself up.
6189  std::unique_ptr<OTAccount> theSourceAcctSmrtPtr(pSourceAcct);
6190 
6191  OTAccount* pRecipientAcct =
6192  OTAccount::LoadExistingAccount(RECIPIENT_ACCT_ID, SERVER_ID);
6193 
6194  if (nullptr == pRecipientAcct) {
6195  otOut << "OTCronItem::MoveFunds: ERROR verifying existence of "
6196  "recipient account.\n";
6197  FlagForRemoval(); // Remove it from future Cron processing, please.
6198  return false;
6199  }
6200  // Past this point we know pRecipientAcct is good and will clean itself up.
6201  std::unique_ptr<OTAccount> theRecipAcctSmrtPtr(pRecipientAcct);
6202 
6203  // BY THIS POINT, both accounts are successfully loaded, and I don't have to
6204  // worry about
6205  // cleaning either one of them up, either. But I can now use pSourceAcct and
6206  // pRecipientAcct...
6207 
6208  // A few verification if/elses...
6209 
6210  // Are both accounts of the same Asset Type?
6211  if (pSourceAcct->GetAssetTypeID() !=
6212  pRecipientAcct->GetAssetTypeID()) { // We already know the SUPPOSED
6213  // Asset IDs of these accounts...
6214  // But only once
6215  // the accounts THEMSELVES have been loaded can we VERIFY this to be
6216  // true.
6217  otOut << "OTCronItem::MoveFunds: ERROR - attempted payment between "
6218  "accounts of different "
6219  "asset types.\n";
6220  FlagForRemoval(); // Remove it from future Cron processing, please.
6221  return false;
6222  }
6223 
6224  // I call VerifySignature (WITH SERVER NYM) here since VerifyContractID was
6225  // already called in LoadExistingAccount().
6226  //
6227  else if (!pSourceAcct->VerifySignature(*pServerNym) ||
6228  !VerifyNymAsAgentForAccount(*pSenderNym, *pSourceAcct)) {
6229  otOut << "OTCronItem::MoveFunds: ERROR verifying signature or "
6230  "ownership on source account.\n";
6231  FlagForRemoval(); // Remove it from future Cron processing, please.
6232  return false;
6233  }
6234  else if (!pRecipientAcct->VerifySignature(*pServerNym) ||
6235  !VerifyNymAsAgentForAccount(*pRecipientNym, *pRecipientAcct)) {
6236  otOut << "OTCronItem::MoveFunds: ERROR verifying signature or "
6237  "ownership on recipient account.\n";
6238  FlagForRemoval(); // Remove it from future Cron processing, please.
6239  return false;
6240  }
6241 
6242  // By this point, I know I have both accounts loaded, and I know that they
6243  // have the right asset types,
6244  // and I know they have the right owners and they were all signed by the
6245  // server.
6246  // I also know that their account IDs in their internal records matched the
6247  // account filename for each acct.
6248  // I also have pointers to the Nyms who own these accounts.
6249  else {
6250  // Okay then, everything checks out. Let's add a receipt to the sender's
6251  // inbox and the recipient's inbox.
6252  // IF they can be loaded up from file, or generated, that is.
6253 
6254  // Load the inboxes in case they already exist
6255  OTLedger theSenderInbox(SENDER_USER_ID, SOURCE_ACCT_ID, SERVER_ID),
6256  theRecipientInbox(RECIPIENT_USER_ID, RECIPIENT_ACCT_ID, SERVER_ID);
6257 
6258  // ALL inboxes -- no outboxes. All will receive notification of
6259  // something ALREADY DONE.
6260  bool bSuccessLoadingSenderInbox = theSenderInbox.LoadInbox();
6261  bool bSuccessLoadingRecipientInbox = theRecipientInbox.LoadInbox();
6262 
6263  // ...or generate them otherwise...
6264 
6265  if (true == bSuccessLoadingSenderInbox)
6266  bSuccessLoadingSenderInbox =
6267  theSenderInbox.VerifyAccount(*pServerNym);
6268  else
6269  otErr << "OTCronItem::MoveFunds: ERROR loading sender inbox "
6270  "ledger.\n";
6271  // else
6272  // bSuccessLoadingSenderInbox =
6273  // theSenderInbox.GenerateLedger(SOURCE_ACCT_ID, SERVER_ID,
6274  // OTLedger::inbox, true); // bGenerateFile=true
6275 
6276  if (true == bSuccessLoadingRecipientInbox)
6277  bSuccessLoadingRecipientInbox =
6278  theRecipientInbox.VerifyAccount(*pServerNym);
6279  else
6280  otErr << "OTCronItem::MoveFunds: ERROR loading recipient inbox "
6281  "ledger.\n";
6282  // else
6283  // bSuccessLoadingRecipientInbox =
6284  // theRecipientInbox.GenerateLedger(RECIPIENT_ACCT_ID, SERVER_ID,
6285  // OTLedger::inbox, true); // bGenerateFile=true
6286 
6287  if ((false == bSuccessLoadingSenderInbox) ||
6288  (false == bSuccessLoadingRecipientInbox)) {
6289  otErr << "OTCronItem::MoveFunds: ERROR loading or generating one "
6290  "(or both) of the inbox ledgers.\n";
6291  }
6292  else {
6293  // Generate new transaction numbers for these new transactions
6294  int64_t lNewTransactionNumber =
6296 
6297  // OT_ASSERT(lNewTransactionNumber > 0); // this can be
6298  // my reminder.
6299  if (0 == lNewTransactionNumber) {
6300  otOut << "OTCronItem::MoveFunds: Aborted move: There are no "
6301  "more transaction numbers available.\n";
6302  // (Here I do NOT flag for removal.)
6303  return false;
6304  }
6305 
6306  OTTransaction* pTransSend = OTTransaction::GenerateTransaction(
6307  theSenderInbox, OTTransaction::paymentReceipt,
6308  lNewTransactionNumber);
6309 
6310  OTTransaction* pTransRecip = OTTransaction::GenerateTransaction(
6311  theRecipientInbox, OTTransaction::paymentReceipt,
6312  lNewTransactionNumber);
6313 
6314  // (No need to OT_ASSERT on the above transactions since it occurs
6315  // in GenerateTransaction().)
6316 
6317  // Both inboxes will get receipts with the same (new) transaction ID
6318  // on them.
6319  // They will have a "In reference to" field containing the original
6320  // payment plan
6321  // (with user's signature).
6322 
6323  // set up the transaction items (each transaction may have multiple
6324  // items... but not in this case.)
6325  OTItem* pItemSend = OTItem::CreateItemFromTransaction(
6326  *pTransSend, OTItem::paymentReceipt);
6327  OTItem* pItemRecip = OTItem::CreateItemFromTransaction(
6328  *pTransRecip, OTItem::paymentReceipt);
6329 
6330  // these may be unnecessary, I'll have to check
6331  // CreateItemFromTransaction. I'll leave em.
6332  OT_ASSERT(nullptr != pItemSend);
6333  OT_ASSERT(nullptr != pItemRecip);
6334 
6335  pItemSend->SetStatus(OTItem::rejection); // the default.
6336  pItemRecip->SetStatus(OTItem::rejection); // the default.
6337 
6338  const int64_t lTransSendRefNo = GetOpeningNumber(SENDER_USER_ID);
6339  const int64_t lTransRecipRefNo =
6340  GetOpeningNumber(RECIPIENT_USER_ID);
6341 
6342  // Here I make sure that each receipt (each inbox notice) references
6343  // the original
6344  // transaction number that was used to set the cron item into
6345  // place...
6346  // This number is used to track all cron items. (All Cron items
6347  // require a transaction
6348  // number from the user in order to add them to Cron in the first
6349  // place.)
6350  //
6351  // The number is also used to uniquely identify all other
6352  // transactions, as you
6353  // might guess from its name.
6354  //
6355  // UPDATE: Notice I'm now looking up different numbers based on the
6356  // UserIDs.
6357  // This is to support smart contracts, which have many parties,
6358  // agents, and accounts.
6359  //
6360  // pItemSend->SetReferenceToNum(lTransSendRefNo);
6361  // pItemRecip->SetReferenceToNum(lTransRecipRefNo);
6362 
6363  pTransSend->SetReferenceToNum(lTransSendRefNo);
6364  pTransRecip->SetReferenceToNum(lTransRecipRefNo);
6365 
6366  // The TRANSACTION (a receipt in my inbox) will be sent with "In
6367  // Reference To" information
6368  // containing the ORIGINAL SIGNED CRON ITEM. (With both parties'
6369  // original signatures on it.)
6370  //
6371  // Whereas the TRANSACTION ITEM will include an "attachment"
6372  // containing the UPDATED
6373  // CRON ITEM (this time with the SERVER's signature on it.)
6374  //
6375  // Here's the original one going onto the transaction:
6376  //
6377  pTransSend->SetReferenceString(strOrigPlan);
6378  pTransRecip->SetReferenceString(strOrigPlan);
6379 
6380  // MOVE THE DIGITAL ASSETS FROM ONE ACCOUNT TO ANOTHER...
6381 
6382  // Calculate the amount and debit/ credit the accounts
6383  // Make sure each Account can afford it, and roll back in case of
6384  // failure.
6385 
6386  // Make sure he can actually afford it...
6387  if (pSourceAcct->GetBalance() >= lAmount) {
6388  // Debit the source account.
6389  bool bMoveSender = pSourceAcct->Debit(lAmount);
6390  bool bMoveRecipient = false;
6391 
6392  // IF success, credit the recipient.
6393  if (bMoveSender) {
6394  bMoveRecipient =
6395  pRecipientAcct->Credit(lAmount); // <=== CREDIT FUNDS
6396 
6397  // Okay, we already took it from the source account.
6398  // But if we FAIL to credit the recipient, then we need to
6399  // PUT IT BACK in the source acct.
6400  // (EVEN THOUGH we'll just "NOT SAVE" after any failure, so
6401  // it's really superfluous.)
6402  //
6403  if (!bMoveRecipient)
6404  pSourceAcct->Credit(lAmount); // put the money back
6405  else
6406  bSuccess = true;
6407  }
6408 
6409  // If ANY of these failed, then roll them all back and break.
6410  if (!bMoveSender || !bMoveRecipient) {
6411  otErr << "OTCronItem::MoveFunds: Very strange! Funds were "
6412  "available but "
6413  "debit or credit failed while performing move.\n";
6414  // We won't save the files anyway, if this failed.
6415  bSuccess = false;
6416  }
6417  }
6418 
6419  // DO NOT SAVE ACCOUNTS if bSuccess is false.
6420  // We only save these accounts if bSuccess == true.
6421  // (But we do save the inboxes either way, since payment failures
6422  // always merit an inbox notice.)
6423 
6424  if (true == bSuccess) // The payment succeeded.
6425  {
6426  // Both accounts involved need to get a receipt of this trade in
6427  // their inboxes...
6428  pItemSend->SetStatus(OTItem::acknowledgement); // pSourceAcct
6429  pItemRecip->SetStatus(
6430  OTItem::acknowledgement); // pRecipientAcct
6431 
6432  pItemSend->SetAmount(lAmount * (-1)); // "paymentReceipt" is
6433  // otherwise ambigious
6434  // about whether you are
6435  // paying or being paid.
6436  pItemRecip->SetAmount(lAmount); // So, I decided for payment and
6437  // market receipts, to use
6438  // negative and positive
6439  // amounts.
6440  // I will probably do the same for cheques, since they can be
6441  // negative as well (invoices).
6442 
6443  otLog3 << "OTCronItem::MoveFunds: Move performed.\n";
6444 
6445  // (I do NOT save m_pCron here, since that already occurs after
6446  // this function is called.)
6447  }
6448  else // bSuccess = false. The payment failed.
6449  {
6450  pItemSend->SetStatus(OTItem::rejection); // pSourceAcct
6451  // // These are already
6452  // initialized to
6453  // false.
6454  pItemRecip->SetStatus(OTItem::rejection); // pRecipientAcct
6455  // // (But just making
6456  // sure...)
6457 
6458  pItemSend->SetAmount(
6459  0); // No money changed hands. Just being explicit.
6460  pItemRecip->SetAmount(
6461  0); // No money changed hands. Just being explicit.
6462 
6463  otLog3 << "OTCronItem::MoveFunds: Move failed.\n";
6464  }
6465 
6466  // Everytime a payment processes, a receipt is put in the user's
6467  // inbox, containing a
6468  // CURRENT copy of the cron item (which took just money from the
6469  // user's acct, or not,
6470  // and either way thus updated its status -- so its internal data
6471  // has changed.)
6472  //
6473  // It will also contain a copy of the user's ORIGINAL signed cron
6474  // item, where the data
6475  // has NOT changed, (so the user's original signature is still
6476  // good.)
6477  //
6478  // In order for it to export the RIGHT VERSION of the CURRENT plan,
6479  // which has just changed
6480  // (above), then I need to re-sign it and save it first. (The
6481  // original version I'll load from
6482  // a separate file using
6483  // OTCronItem::LoadCronReceipt(lTransactionNum).
6484  //
6485  // I should be able to call a method on the original cronitem, where
6486  // I ask it to verify a certain
6487  // nym as being acceptable to that cron item as an agent, based on
6488  // the signature of the original
6489  // authorizing agent for that party.
6490  //
6491 
6493  SignContract(*pServerNym);
6494  SaveContract();
6495 
6496  // This is now at the bottom of this function.
6497  //
6498  // m_pCron->SaveCron(); // Cron is where I am serialized, so if
6499  // Cron's not saved, I'm not saved.
6500 
6501  //
6502  // EVERYTHING BELOW is just about notifying the users, by dropping
6503  // the receipt in their
6504  // inboxes. The rest is done. The accounts and inboxes will all be
6505  // saved at the same time.
6506  //
6507  // The Payment Plan is entirely updated and saved by this point, and
6508  // Cron will
6509  // also be saved in the calling function once we return (no matter
6510  // what.)
6511  //
6512 
6513  // Basically I load up both INBOXES, which are actually LEDGERS, and
6514  // then I create
6515  // a new transaction, with a new transaction item, for each of the
6516  // ledgers.
6517  // (That's where the receipt information goes.)
6518  //
6519 
6520  // The TRANSACTION will be sent with "In Reference To" information
6521  // containing the
6522  // ORIGINAL SIGNED PLAN. (With both of the users' original
6523  // signatures on it.)
6524  //
6525  // Whereas the TRANSACTION ITEM will include an "attachment"
6526  // containing the UPDATED
6527  // PLAN (this time with the SERVER's signature on it.)
6528 
6529  // (Lucky I just signed and saved the updated plan (above), or it
6530  // would still have
6531  // have the old data in it.)
6532 
6533  // I also already loaded the original plan. Remember this from
6534  // above,
6535  // near the top of the function:
6536  // OTCronItem * pOrigCronItem = nullptr;
6537  // OTString strOrigPlan(*pOrigCronItem); // <====== Farther down
6538  // in the code, I attach this string to the receipts.
6539  // ... then lower down...
6540  // pTransSend->SetReferenceString(strOrigPlan);
6541  // pTransRecip->SetReferenceString(strOrigPlan);
6542  //
6543  // So the original plan is already loaded and copied to the
6544  // Transaction as the "In Reference To"
6545  // Field. Now let's add the UPDATED plan as an ATTACHMENT on the
6546  // Transaction ITEM:
6547  //
6548  OTString strUpdatedCronItem(*this);
6549 
6550  // Set the updated cron item as the attachment on the transaction
6551  // item.
6552  // (With the SERVER's signature on it!)
6553  // (As a receipt for each party, so they can see their smartcontract
6554  // updating.)
6555  //
6556  pItemSend->SetAttachment(strUpdatedCronItem);
6557  pItemRecip->SetAttachment(strUpdatedCronItem);
6558 
6559  // Success OR failure, either way I want a receipt in both inboxes.
6560  // But if FAILURE, I do NOT want to save the Accounts, JUST the
6561  // inboxes.
6562  // So the inboxes happen either way, but the accounts are saved only
6563  // on success.
6564 
6565  // sign the item
6566  pItemSend->SignContract(*pServerNym);
6567  pItemRecip->SignContract(*pServerNym);
6568 
6569  pItemSend->SaveContract();
6570  pItemRecip->SaveContract();
6571 
6572  // the Transaction "owns" the item now and will handle cleaning it
6573  // up.
6574  pTransSend->AddItem(*pItemSend);
6575  pTransRecip->AddItem(*pItemRecip);
6576 
6577  pTransSend->SignContract(*pServerNym);
6578  pTransRecip->SignContract(*pServerNym);
6579 
6580  pTransSend->SaveContract();
6581  pTransRecip->SaveContract();
6582 
6583  // Here, the transactions we just created are actually added to the
6584  // ledgers.
6585  // This happens either way, success or fail.
6586 
6587  theSenderInbox.AddTransaction(*pTransSend);
6588  theRecipientInbox.AddTransaction(*pTransRecip);
6589 
6590  // Release any signatures that were there before (They won't
6591  // verify anymore anyway, since the content has changed.)
6592  theSenderInbox.ReleaseSignatures();
6593  theRecipientInbox.ReleaseSignatures();
6594 
6595  // Sign both of them.
6596  theSenderInbox.SignContract(*pServerNym);
6597  theRecipientInbox.SignContract(*pServerNym);
6598 
6599  // Save both of them internally
6600  theSenderInbox.SaveContract();
6601  theRecipientInbox.SaveContract();
6602 
6603  // Save both inboxes to storage. (File, DB, wherever it goes.)
6604  pSourceAcct->SaveInbox(theSenderInbox);
6605  pRecipientAcct->SaveInbox(theRecipientInbox);
6606 
6607  // These correspond to the AddTransaction() calls, just above
6608  //
6609  pTransSend->SaveBoxReceipt(theSenderInbox);
6610  pTransRecip->SaveBoxReceipt(theRecipientInbox);
6611 
6612  // If success, save the accounts with new balance. (Save inboxes
6613  // with receipts either way,
6614  // and the receipts will contain a rejection or acknowledgment
6615  // stamped by the Server Nym.)
6616  if (true == bSuccess) {
6617 
6618  // Release any signatures that were there before (They won't
6619  // verify anymore anyway, since the content has changed.)
6620  pSourceAcct->ReleaseSignatures();
6621  pRecipientAcct->ReleaseSignatures();
6622 
6623  // Sign both of them.
6624  pSourceAcct->SignContract(*pServerNym);
6625  pRecipientAcct->SignContract(*pServerNym);
6626 
6627  // Save both of them internally
6628  pSourceAcct->SaveContract();
6629  pRecipientAcct->SaveContract();
6630 
6631  // TODO: Better rollback capabilities in case of failures here:
6632 
6633  // Save both accounts to storage.
6634  pSourceAcct->SaveAccount();
6635  pRecipientAcct->SaveAccount();
6636 
6637  // NO NEED TO LOG HERE, since success / failure is already
6638  // logged above.
6639  }
6640  } // both inboxes were successfully loaded or generated.
6641  } // By the time we enter this block, accounts and nyms are already loaded.
6642  // As we begin, inboxes are instantiated.
6643 
6644  // Todo: possibly notify ALL parties here (in Nymbox.)
6645 
6646  // Either way, Cron should save, since it just updated.
6647  // The above function WILL change this smart contract.
6648  // and re-sign it and save it, no matter what. So I just
6649  // call this here to keep it simple:
6650 
6651  GetCron()->SaveCron();
6652 
6653  return bSuccess;
6654 }
6655 
6656 } // namespace opentxs
OTParty * FindPartyBasedOnNymIDAsAgent(const OTIdentifier &theNymID, OTAgent **ppAgent=nullptr) const
virtual void GetAllTransactionNumbers(OTNumList &numlistOutput) const
int64_t GetNextTransactionNumber()
Definition: OTCron.cpp:422
bool DropFinalReceiptToNymboxes(const int64_t &lNewTransactionNumber, const OTString &strOrigCronItem, OTString *pstrNote=nullptr, OTString *pstrAttachment=nullptr, OTPseudonym *pActualNym=nullptr)
Definition: OTParty.cpp:1014
void SetAmount(int64_t lAmount)
Definition: OTItem.hpp:479
#define SMARTCONTRACT_HOOK_ON_ACTIVATE
bool LoadAndVerifyAgentNyms(OTPseudonym &theServerNym, mapOfNyms &map_Nyms_Already_Loaded, mapOfNyms &map_NewlyLoaded)
Definition: OTParty.cpp:1197
static EXPORT int64_t StringToLong(const std::string &number)
Definition: OTString.cpp:677
bool HasTransactionNum(const int64_t &lInput) const
Definition: OTParty.cpp:150
int32_t GetCountStashAccts() const
OTStashItem * GetStash(const std::string &str_asset_type_id)
Definition: OTStash.cpp:275
static EXPORT OTTransaction * GenerateTransaction(const OTIdentifier &theUserID, const OTIdentifier &theAccountID, const OTIdentifier &theServerID, transactionType theType, int64_t lTransactionNum=0)
bool VerifyAccountsWithTheirAgents(OTPseudonym &theSignerNym, const OTString &strServerID, bool bBurnTransNo=false)
Definition: OTParty.cpp:1370
virtual EXPORT bool AddParty(OTParty &theParty)
std::string GetRemainingTimer() const
EXPORT std::string GetPartyName(bool *pBoolSuccess=nullptr) const
Definition: OTParty.cpp:489
bool LoadAndVerifyAssetAccounts(OTPseudonym &theServerNym, const OTString &strServerID, mapOfAccounts &map_Accts_Already_Loaded, mapOfAccounts &map_NewlyLoaded)
Definition: OTParty.cpp:1094
EXPORT bool StashFunds(const mapOfNyms &map_NymsAlreadyLoaded, const int64_t &lAmount, const OTIdentifier &PARTY_ACCT_ID, const OTIdentifier &PARTY_USER_ID, OTStash &theStash)
EXPORT bool SaveCron()
Definition: OTCron.cpp:179
EXPORT void RegisterForExecution(OTScript &theScript)
Definition: OTVariable.cpp:424
EXPORT bool SendNoticeToAllParties(bool bSuccessMsg, OTPseudonym &theServerNym, const OTIdentifier &theServerID, const int64_t &lNewTransactionNumber, const OTString &strReference, OTString *pstrNote=nullptr, OTString *pstrAttachment=nullptr, OTPseudonym *pActualNym=nullptr) const
const OTIdentifier & GetSenderUserID() const
OTStash * GetStash(std::string str_stash_name)
EXPORT void GetIdentifier(OTIdentifier &theIdentifier) const
std::string GetAssetTypeIDofAcct(std::string from_acct_name)
bool(OTSmartContract::* OT_SM_RetBool_ThrStr)(std::string from_acct_name, std::string to_acct_name, std::string str_Amount)
time64_t GetValidTo() const
EXPORT bool VerifySmartContract(OTPseudonym &theNym, OTAccount &theAcct, OTPseudonym &theServerNym, bool bBurnTransNo=false)
EXPORT OTParty * FindPartyBasedOnNymAsAuthAgent(OTPseudonym &theNym, OTAgent **ppAgent=nullptr) const
virtual int32_t ProcessXMLNode(irr::io::IrrXMLReader *&xml)
void SetValidFrom(time64_t TIME_FROM)
virtual void onFinalReceipt(OTCronItem &theOrigCronItem, const int64_t &lNewTransactionNumber, OTPseudonym &theOriginator, OTPseudonym *pRemover)
virtual void RegisterOTNativeCallsWithScript(OTScript &theScript)
virtual EXPORT bool VerifyAccount(const OTPseudonym &theNym)
Definition: OTLedger.cpp:187
EXPORT const OTIdentifier & GetAssetTypeID() const
Definition: OTAccount.cpp:449
int64_t GetTransactionNum() const
EXPORT void RegisterVariablesForExecution(OTScript &theScript)
Definition: OTBylaw.cpp:276
EXPORT int64_t GetBalance() const
Definition: OTAccount.cpp:664
EXPORT bool VerifyOwnerByID(const OTIdentifier &nymId) const
Definition: OTAccount.cpp:472
void ClearTemporaryPointers()
Definition: OTParty.cpp:468
bool ReserveTransNumsForConfirm(const OTString &strServerID)
Definition: OTParty.cpp:1631
int64_t OTTimeGetTimeInterval(time64_t lhs, time64_t rhs)
Definition: Common.hpp:234
virtual int32_t ProcessXMLNode(irr::io::IrrXMLReader *&xml)
EXPORT bool SaveContract()
EXPORT bool VerifyIssuedNum(const OTString &strServerID, const int64_t &lTransNum) const
time64_t OTTimeAddTimeInterval(time64_t lhs, int64_t rhs)
Definition: Common.hpp:238
EXPORT int64_t ToLong() const
Definition: OTString.cpp:702
virtual void HarvestOpeningNumber(OTPseudonym &theNym)
EXPORT bool LoadInbox()
Definition: OTLedger.cpp:463
bool SendNoticeToParty(bool bSuccessMsg, OTPseudonym &theServerNym, const OTIdentifier &theServerID, const int64_t &lNewTransactionNumber, const OTString &strReference, OTString *pstrNote=nullptr, OTString *pstrAttachment=nullptr, OTPseudonym *pActualNym=nullptr)
Definition: OTParty.cpp:1057
static EXPORT OTCronItem * LoadCronReceipt(const int64_t &lTransactionNum)
Definition: OTCronItem.cpp:227
std::map< std::string, OTVariable * > mapOfVariables
Definition: OTBylaw.hpp:146
virtual EXPORT void RegisterOTNativeCallsWithScript(OTScript &theScript)
bool IsFlaggedForRemoval() const
Definition: OTCronItem.hpp:238
void CloseoutOpeningNumber(const OTString &strServerID, bool bSave=false, OTPseudonym *pSignerNym=nullptr)
Definition: OTParty.cpp:1595
bool GetSignerID(OTIdentifier &theOutput) const
Definition: OTAgent.cpp:514
bool CanCancelContract(std::string str_party_name)
EXPORT bool AddTransaction(OTTransaction &theTransaction)
Definition: OTLedger.cpp:1194
#define SMARTCONTRACT_HOOK_ON_PROCESS
OTLOG_IMPORT OTLogStream otOut
std::map< std::string, OTPseudonym * > mapOfNyms
Definition: OTWallet.hpp:161
virtual EXPORT bool Compare(OTScriptable &rhs) const
std::string GetStashBalance(std::string stash_name, std::string asset_type_id)
const OTIdentifier & GetServerID() const
Definition: OTCron.hpp:293
OTLOG_IMPORT OTLogStream otLog3
EXPORT void SetAttachment(const OTString &theStr)
Definition: OTItem.cpp:1402
bool CopyValueBool() const
Definition: OTVariable.hpp:250
EXPORT std::shared_ptr< OTAccount > GetOrCreateAccount(OTPseudonym &serverNym, const OTIdentifier &ACCOUNT_OWNER_ID, const OTIdentifier &ASSET_TYPE_ID, const OTIdentifier &SERVER_ID, bool &wasAcctCreated, int64_t stashTransNum=0)
std::map< std::string, OTClause * > mapOfClauses
Definition: OTBylaw.hpp:145
virtual void SetDisplayLabel(const std::string *pstrLabel=nullptr)
#define SMART_CONTRACT_PROCESS_INTERVAL
void SetValidTo(time64_t TIME_TO)
time64_t OTTimeGetTimeFromSeconds(int64_t seconds)
Definition: Common.hpp:215
EXPORT bool LoadSignedNymfile(OTPseudonym &SIGNER_NYM)
EXPORT int32_t ReadFromXMLNode(irr::io::IrrXMLReader *&xml, const OTString &acctType, const OTString &acctCount)
void CloseoutOpeningNumbers(OTPseudonym *pSignerNym=nullptr)
EXPORT const OTString & GetName() const
Definition: OTClause.hpp:155
void HarvestOpeningNumber(const OTString &strServerID)
Definition: OTParty.cpp:1568
EXPORT void Concatenate(const char *arg,...)
Definition: OTString.cpp:1334
int64_t time64_t
Definition: Common.hpp:209
EXPORT OTAgent * GetAuthorizedAgent()
EXPORT bool VerifyCurrentDate()
EXPORT int32_t GetCountAccountIDs() const
EXPORT int32_t GetTransactionNumCount(const OTIdentifier &theServerID) const
void SetCreationDate(const time64_t &CREATION_DATE)
Definition: OTCronItem.hpp:264
mapOfParties m_mapParties
EXPORT int64_t GetClosingTransactionNoAt(uint32_t nIndex) const
Definition: OTCronItem.cpp:681
EXPORT bool VerifyPseudonym() const
int64_t GetAmount() const
static EXPORT OTItem * CreateItemFromTransaction(const OTTransaction &theOwner, OTItem::itemType theType, const OTIdentifier *pDestinationAcctID=nullptr)
Definition: OTItem.cpp:1451
const time64_t & GetNextProcessDate() const
EXPORT void ReleaseSignatures()
Definition: OTContract.cpp:989
EXPORT bool Exists() const
Definition: OTString.cpp:1035
EXPORT void SetString(const char *szString)
EXPORT void SetIdentifier(const OTIdentifier &theIdentifier)
virtual bool CanRemoveItemFromCron(OTPseudonym &theNym)
const OTIdentifier & GetServerID() const
EXPORT void Format(const char *fmt,...)
Definition: OTString.cpp:1319
void SetStatus(const OTItem::itemStatus &theVal)
Definition: OTItem.hpp:463
void HarvestClosingNumbers(const OTString &strServerID, bool bSave=false, OTPseudonym *pSignerNym=nullptr)
Definition: OTParty.cpp:1449
time64_t GetValidFrom() const
EXPORT bool LoadPublicKey()
const OTIdentifier & GetRealAccountID() const
void SetNextProcessDate(const time64_t &tNEXT_DATE)
EXPORT void SetReferenceString(const OTString &theStr)
bool ExecuteCallback(OTClause &theCallbackClause, mapOfVariables &theParameters, OTVariable &varReturnVal)
EXPORT void PrepareToActivate(const int64_t &lOpeningTransNo, const int64_t &lClosingTransNo, const OTIdentifier &theUserID, const OTIdentifier &theAcctID)
EXPORT int32_t GetCountClosingNumbers() const
Definition: OTCronItem.cpp:676
EXPORT const OTString & GetName()
Definition: OTAgent.hpp:388
bool VerifyPartyAuthorization(OTParty &theParty, OTPseudonym &theSignerNym, const OTString &strServerID, mapOfNyms *pmap_ALREADY_LOADED=nullptr, mapOfNyms *pmap_NEWLY_LOADED=nullptr, bool bBurnTransNo=false)
virtual bool IsValidOpeningNumber(const int64_t &lOpeningNum) const
time64_t OTTimeGetCurrentTime()
Definition: Common.hpp:211
void UpdateContentsToString(OTString &strAppend, bool bCalculatingID) const
virtual bool ProcessCron()
Definition: OTCronItem.cpp:769
OTPseudonym * LoadAuthorizingAgentNym(OTPseudonym &theSignerNym, OTAgent **ppAgent=nullptr)
Definition: OTParty.cpp:899
EXPORT const char * GetCode() const
Definition: OTClause.cpp:177
int32_t ReadFromXMLNode(irr::io::IrrXMLReader *&xml, const OTString &strStashName, const OTString &strItemCount)
Definition: OTStash.cpp:165
EXPORT bool RemoveIssuedNum(OTPseudonym &SIGNER_NYM, const OTString &strServerID, const int64_t &lTransNum, bool bSave)
void SetTransactionNum(int64_t lTransactionNum)
#define OT_ASSERT(x)
Definition: Assert.hpp:150
void RetrieveNymPointers(mapOfNyms &map_Nyms_Already_Loaded)
static void CleanupAccts(mapOfAccounts &theMap)
static void CleanupNyms(mapOfNyms &theMap)
OTString m_strContractType
Definition: OTContract.hpp:178
#define OT_ASSERT_MSG(x, s)
Definition: Assert.hpp:155
std::map< std::string, OTAccount * > mapOfAccounts
Definition: OTWallet.hpp:157
OTClause * GetCallback(std::string str_CallbackName)
OTLOG_IMPORT OTLogStream otInfo
EXPORT OTParty * GetParty(std::string str_party_name) const
EXPORT bool CompareID(const OTIdentifier &theIdentifier) const
const OTString & GetAgentName() const
bool DebitStash(const int64_t &lAmount)
EXPORT std::string GetPartyID(bool *pBoolSuccess=nullptr) const
Definition: OTParty.cpp:571
int32_t GetCountStashes() const
const int64_t & GetProcessInterval() const
Definition: OTCronItem.hpp:288
void SetSenderAcctID(const OTIdentifier &ACCT_ID)
bool DropFinalReceiptToInboxes(mapOfNyms *pNymMap, const OTString &strServerID, OTPseudonym &theServerNym, const int64_t &lNewTransactionNumber, const OTString &strOrigCronItem, OTString *pstrNote=nullptr, OTString *pstrAttachment=nullptr)
Definition: OTParty.cpp:967
EXPORT OTVariable * GetVariable(std::string str_Name)
Definition: OTBylaw.cpp:579
OTStringXML m_xmlUnsigned
Definition: OTContract.hpp:174
virtual bool HasTransactionNum(const int64_t &lInput) const
#define OT_FAIL_MSG(s)
Definition: Assert.hpp:144
EXPORT bool SaveBoxReceipt(int64_t lLedgerType)
OTLOG_IMPORT OTLogStream otWarn
virtual bool AddParty(OTParty &theParty)
EXPORT void Release()
EXPORT const char * Get() const
Definition: OTString.cpp:1045
void Serialize(OTString &strAppend) const
Definition: OTStash.cpp:147
virtual bool ConfirmParty(OTParty &theParty)
virtual EXPORT bool SignContract(const OTPseudonym &theNym, const OTPasswordData *pPWData=nullptr)
Definition: OTContract.cpp:484
EXPORT bool SaveInbox(OTLedger &box, OTIdentifier *hash=nullptr)
Definition: OTAccount.cpp:260
void SetServerID(const OTIdentifier &SERVER_ID)
EXPORT bool IsAnIndividual() const
Definition: OTAgent.cpp:390
OTLOG_IMPORT OTLogStream otErr
EXPORT void Serialize(OTString &append) const
OTBylaw * GetBylaw() const
Definition: OTClause.hpp:160
virtual void HarvestClosingNumbers(OTPseudonym &theNym)
const OTString & GetAcctID() const
EXPORT void SetReferenceToNum(int64_t lTransactionNum)
OTIdentifier * m_pCancelerNymID
Definition: OTCronItem.hpp:177
EXPORT const char * GetLanguage() const
Definition: OTBylaw.cpp:916
virtual bool Compare(OTScriptable &rhs) const
OTPseudonym * GetServerNym() const
Definition: OTCron.hpp:303
EXPORT void ExecuteClauses(mapOfClauses &theClauses, OTString *pParam=nullptr)
EXPORT void GetString(OTString &theStr) const
virtual bool SaveContractWallet(std::ofstream &ofs) const
virtual int64_t GetOpeningNumber(const OTIdentifier &theNymID) const
virtual EXPORT bool VerifySignature(const OTPseudonym &theNym, const OTPasswordData *pPWData=nullptr) const
Definition: OTContract.cpp:818
const OTIdentifier & GetSenderAcctID() const
const time64_t & GetLastProcessDate() const
Definition: OTCronItem.hpp:279
virtual EXPORT bool VerifyNymAsAgentForAccount(OTPseudonym &theNym, OTAccount &theAccount) const
bool IsDirtyImportant() const
std::set< int64_t > & GetSetOpenCronItems()
int64_t GetOpeningTransNo() const
Definition: OTParty.hpp:295
int64_t GetClosingTransNo() const
EXPORT OTParty * FindPartyBasedOnNymAsAgent(OTPseudonym &theNym, OTAgent **ppAgent=nullptr) const
void HarvestAllTransactionNumbers(const OTString &strServerID)
Definition: OTParty.cpp:1587
void SetSenderUserID(const OTIdentifier &USER_ID)
void SetRemainingTimer(std::string str_seconds_from_now)
bool HasActiveAgent() const
Definition: OTParty.cpp:592
int64_t OTTimeGetSecondsFromTime(time64_t time)
Definition: Common.hpp:230
EXPORT void AddClosingTransactionNo(const int64_t &lClosingTransactionNo)
Definition: OTCronItem.cpp:693
bool SendNoticeToParty(std::string party_name)
bool GetHooks(std::string str_HookName, mapOfClauses &theResults)
#define OT_TIME_ZERO
Definition: Common.hpp:180
bool CreditStash(const int64_t &lAmount)
std::string GetAcctBalance(std::string from_acct_name)
int64_t GetAmount(std::string str_asset_type_id)
Definition: OTStash.cpp:297
virtual EXPORT void Release()
Definition: OTData.cpp:257
OTCron * GetCron() const
Definition: OTCronItem.hpp:293
OTPartyAccount * GetPartyAccountByID(const OTIdentifier &theAcctID) const
bool UnstashAcctFunds(std::string to_acct_name, std::string from_stash_name, std::string str_Amount)
EXPORT bool SaveAccount()
Definition: OTAccount.cpp:379
OTPartyAccount * GetPartyAccount(std::string str_acct_name) const
virtual EXPORT bool ConfirmParty(OTParty &theParty)
OTParty * GetParty() const
Definition: OTAgent.hpp:414
virtual EXPORT ~OTSmartContract()
EXPORT bool Credit(const int64_t &amount)
Definition: OTAccount.cpp:415
static EXPORT OTAccount * LoadExistingAccount(const OTIdentifier &accountId, const OTIdentifier &serverId)
Definition: OTAccount.cpp:480
EXPORT bool Debit(const int64_t &amount)
Definition: OTAccount.cpp:388
virtual EXPORT void Release()
Definition: OTString.cpp:765
virtual void Release()
EXPORT std::shared_ptr< OTScript > OTScriptFactory(const std::string &script_type="")
Definition: OTScript.cpp:203
void GetAllTransactionNumbers(OTNumList &numlistOutput) const
Definition: OTParty.cpp:165
virtual int64_t GetClosingNumber(const OTIdentifier &theAcctID) const
void SetProcessInterval(const int64_t &THE_DATE)
Definition: OTCronItem.hpp:284
bool StashAcctFunds(std::string from_acct_name, std::string to_stash_name, std::string str_Amount)
EXPORT void AddItem(OTItem &theItem)
#define SMARTCONTRACT_CALLBACK_PARTY_MAY_CANCEL
EXPORT bool SaveSignedNymfile(OTPseudonym &SIGNER_NYM)
const time64_t & GetCreationDate() const
Definition: OTCronItem.hpp:268
bool HasAuthorizingAgent(OTPseudonym &theNym, OTAgent **ppAgent=nullptr) const
Definition: OTParty.cpp:814
bool MoveAcctFundsStr(std::string from_acct_name, std::string to_acct_name, std::string str_Amount)
EXPORT bool SetServerIDIfEmpty(const OTIdentifier &theID)
void SetLastProcessDate(const time64_t &THE_DATE)
Definition: OTCronItem.hpp:275