diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..4086f07 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e3d6c36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +hodl/__pycache__ +node_modules diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100755 index 0000000..e6ab5f8 --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# HODL - smart contract plugin for Electron Cash to timelock the funds +![Logo](/pictures/logo.png) + +Did you ever regret acting under FUD or FOMO influence? + +Did you make big financial mistakes because of that? + +Do you want to protect yourself from such compulsory actions? + +Then you'll certainly want to use the HODL plugin for Electron Cash. With it you can lock your funds in a smart contract utilizing CLTV opcode, rendering them unspendable until a certain date or blockchain height. + +## Quick start + +1. First, download and verify sha256 of the hodl-vVERSION.zip file from [releases](https://github.com/mainnet-pat/hodl_ec_plugin/releases). Then go to your Electron Cash and install the plugin, +2. The plugin tab should show up. Click "Create new HODL contract", choose the amount of BCH you want to lock until either certain blockchain height or certain date. +3. Select the matured contract and click "Spend contract" to release the funds and claim them back to your wallet. + +## Limitations and notices + +1. The plugin is designed only for the standard HD wallets (multiaddress). Watchonly, Multisig wallets or wallets with imported private keys are not supported. + +2. If you lock the funds until certain date, allow for extra time (up to 70 minutes) after the contract maturation. This is due to the median time-past for the lock-time calculations (BIP-113). + +3. HODL contract can safely lock values greater than 21 BCH. + +## Contract details + +### Smart contract basics +The contract is defined by a special address that is cryptographically determined by the contract itself. [Learn more](https://en.bitcoin.it/wiki/Pay_to_script_hash). Funds are "in the contract" when they are sent to this special address. + +A contract consists of challenges - requirements that have to be met to access the funds stored in it. This contract has only one challenge, but several prerequisites to satisfy. + +### HODL contract +HODL contract is a simple upgrade over the most common pay to public key hash (P2PKH) address type. It utilizes in addition the OP_CHECKLOCKTIMEVERIFY opcode to check against the current blockchain height or current date before locking the funds to the redeemer's public key hash. The target locktime is provided to the contract upon its construction as an argument. + +Equivalent contract code in the high-level [cashscript](https://github.com/Bitcoin-com/cashscript) language: +``` +pragma cashscript ^0.6.0; + +contract hodl( + int locktime, + bytes20 pubkeyHash +) { + function spend(pubkey ownerPubkey, sig ownerSig) { + require(tx.time >= locktime); + require(hash160(ownerPubkey) == pubkeyHash); + require(checkSig(ownerSig, ownerPubkey)); + } +} +``` + +The actual script is implemented as follows: +``` +scriptSig: +scriptPubkey: OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG +``` + +Transaction fees are very low and target 1sat/byte. However, they depend upon the number of inputs, as usual. + +## Disclaimer + +The author of this software is not a party to any HODL contract created, have no control over it and cannot influence it's outcome. The author is not responsible for legal implications of the HODL contract nor is competent to settle any disputes. The author is not responsible for the contract expected behavior. + +## License + +This software is distributed on GPL v2 license. The author encourage you to build your own smart contract plugins based on this plugin code, implement desired functions and submit a pull request to this repository or fork this project and compete, if I fail to deliver what you expect. Just remember to publish your improvements on the same license. + +## Contact the author + +With any problems contact me on telegram: **@mainnet_pat**, reddit: **u/mainnet_pat** + +## Donations + +If you wish to support development of the plugin, consider donating to: + +Cash Account: pat#111222 + +bitcoincash:qqsxjha225lmnuedy6hzlgpwqn0fd77dfq73p60wwp + +![donate](/pictures/donate.png) + +## Attributions + +This work is based on the codebase of [Mecenas Electron Cash plugin](https://github.com/KarolTrzeszczkowski/Mecenas-recurring-payment-EC-plugin.git) by licho. + +The diamond logo is taken from [https://icons8.com](https://icons8.com) diff --git a/diamond.png b/diamond.png new file mode 100644 index 0000000..5ed611a Binary files /dev/null and b/diamond.png differ diff --git a/hodl.cash b/hodl.cash new file mode 100644 index 0000000..c754326 --- /dev/null +++ b/hodl.cash @@ -0,0 +1,12 @@ +pragma cashscript ^0.6.0; + +contract hodl( + int locktime, + bytes20 pubkeyHash +) { + function spend(pubkey ownerPubkey, sig ownerSig) { + require(tx.time >= locktime); + require(hash160(ownerPubkey) == pubkeyHash); + require(checkSig(ownerSig, ownerPubkey)); + } +} diff --git a/hodl.v1.0.0.zip b/hodl.v1.0.0.zip new file mode 100644 index 0000000..7f09dc5 Binary files /dev/null and b/hodl.v1.0.0.zip differ diff --git a/hodl/__init__.py b/hodl/__init__.py new file mode 100755 index 0000000..aa3d7bc --- /dev/null +++ b/hodl/__init__.py @@ -0,0 +1,5 @@ +from electroncash.i18n import _ + +fullname = 'HODL' +description = _('Lock your funds and have no FUD') +available_for = ['qt'] diff --git a/hodl/contract.py b/hodl/contract.py new file mode 100644 index 0000000..847c994 --- /dev/null +++ b/hodl/contract.py @@ -0,0 +1,14 @@ + + +class Contract: + def __init__(self, addresses, initial_tx=None, v=0): + self.version = v + self.initial_tx = initial_tx + self.addresses = addresses + + @staticmethod + def participants(version): + pass + @staticmethod + def roles(version): + pass \ No newline at end of file diff --git a/hodl/contract_finder.py b/hodl/contract_finder.py new file mode 100644 index 0000000..2748b4d --- /dev/null +++ b/hodl/contract_finder.py @@ -0,0 +1,116 @@ +import queue +from .hodl_contract import HodlContract +from electroncash import util +from electroncash.address import Address, ScriptOutput +from itertools import permutations, combinations + +def synchronous_get_many(network, requests): + """ modified synchrronous_get to handle batched requests """ + responses = [] + + q = queue.Queue() + network.send(requests, q.put) + try: + for _ in range(0, len(requests)): + response = q.get(True, 30) + if response.get('error'): + raise util.ServerError(response.get('error')) + responses.append(response) + except queue.Empty: + raise util.TimeoutException('Server did not answer') + + return responses + +def find_contract_in_wallet(wallet, contract_cls: HodlContract): + contract_tuple_list=[] + requests = [] + contract_map = {} + + for hash, t in wallet.transactions.items(): + contract = scan_transaction(t, contract_cls) + if contract is None: + continue + + contract_map[contract.address.to_scripthash_hex()] = contract + requests.append(("blockchain.scripthash.listunspent", [contract.address.to_scripthash_hex()])) + + try: + responses = synchronous_get_many(wallet.network, requests) + except Exception as e: + print(e) + responses = [] + + for response in responses: + if unfunded_contract(response['result']): # skip unfunded and ended contracts + continue + + contract = contract_map[response['params'][0]] + + a=contract.addresses + # print("hello there", contract.address.to_ui_string()) + contract_tuple_list.append((response['result'], contract, find_my_role(a, wallet))) + + remove_duplicates(contract_tuple_list) + return contract_tuple_list + +def remove_duplicates(contracts): + c = contracts + for c1, c2 in combinations(contracts,2): + if c1[1].address == c2[1].address: + c.remove(c1) + return c + + +def unfunded_contract(r): + """Checks if the contract is funded""" + s = False + if len(r) == 0: + s = True + for t in r: + if t.get('value') == 0: # when contract was drained it's still in utxo + s = True + return s + + +def scan_transaction(tx, contract_cls: HodlContract): + out = tx.outputs() + address, v, data = parse_p2sh_notification(out, contract_cls) + if address is None or v is None or data is None: + return + no_participants = contract_cls.participants(v) + if no_participants > (len(out)+1): + return None + candidates = get_candidates(out[1:], no_participants) + for c in candidates: + contract = contract_cls(c,tx.as_dict(),v=v, data=data) + if contract.address.to_ui_string() == address: + return contract + + +def parse_p2sh_notification(outputs, contract_cls: HodlContract): + opreturn = outputs[0] + try: + assert isinstance(opreturn[1], ScriptOutput) + assert opreturn[1].to_ui_string().split(",")[1] == f" (4) '{contract_cls.op_return_signature()}'" + a = opreturn[1].to_ui_string().split("'")[3][:42] + version = float(opreturn[1].to_ui_string().split("'")[3][42:]) + data = [int(e) for e in opreturn[1].to_ui_string().split("'")[5].split(' ')] + return Address.from_string(a).to_ui_string(), version, data + except: + return None, None, None + + +def get_candidates(outputs, participants): + """Creates all permutations of addresses that are not p2sh type""" + candidates = [] + for o in permutations(outputs, participants): + kinds = [i[1].kind for i in o] + if 1 in kinds: + continue + addresses = [i[1] for i in o] + candidates.append(addresses) + return candidates + + +def find_my_role(candidates, wallet): + return [0] diff --git a/hodl/hodl_contract.py b/hodl/hodl_contract.py new file mode 100755 index 0000000..257d1c4 --- /dev/null +++ b/hodl/hodl_contract.py @@ -0,0 +1,183 @@ +from electroncash.bitcoin import regenerate_key, MySigningKey, Hash +from electroncash.address import Address, Script, OpCodes as Op +from electroncash.transaction import Transaction,TYPE_ADDRESS +import ecdsa +from .contract import Contract +from math import ceil +import struct + +import time +LOCKTIME_THRESHOLD = 500000000 +UTXO=0 +CONTRACT=1 +MODE=2 +SELF = 0 + + +def joinbytes(iterable): + """Joins an iterable of bytes and/or integers into a single byte string""" + return b''.join((bytes((x,)) if isinstance(x,int) else x) for x in iterable) + +def len_bytes(value): + if isinstance(value, int): + return (value.bit_length() + 7) // 8 + + raise "Unsupported data type" + + +class HodlContract(Contract): + """Hodl Contract implementation""" + def __init__(self, addresses, initial_tx=None,v=0, data=None): + Contract.__init__(self, addresses,initial_tx,v) + try: + self.i_time = data[0] + except: + self.i_time = 0 + + self.i_time_len = len_bytes(self.i_time) + self.i_time_bytes = self.i_time.to_bytes(self.i_time_len, 'little') + + assert self.i_time >= 0 + assert len(self.i_time_bytes) == self.i_time_len + + self.redeemscript_v1 = joinbytes([ + self.i_time_len, self.i_time_bytes, + Op.OP_CHECKLOCKTIMEVERIFY, Op.OP_DROP, + Op.OP_DUP, Op.OP_HASH160, + Script.push_data(addresses[0].hash160), + Op.OP_EQUALVERIFY, Op.OP_CHECKSIG + ]) + + self.redeemscript=self.redeemscript_v1 + self.set_version(v) + self.address = Address.from_multisig_script(self.redeemscript) + data1 = self.address.to_ui_string() + ' ' + str(self.version) + data2 = str(self.i_time) + self.op_return = joinbytes( + [Op.OP_RETURN, 4, self.op_return_signature().encode('utf8'), len(data1), data1.encode('utf8'), len(data2), data2.encode('utf8')]) + + def __eq__(self, o) -> bool: + return self.i_time == o.i_time and \ + self.address == o.address and \ + self.addresses[0] == o.addresses[0] + + @staticmethod + def op_return_signature(): + """4 byte string to distinguish the contract""" + return "hodl" + + @staticmethod + def participants(version): + return 1 + + @staticmethod + def fee(version): + """Top fee estimate""" + return 1000 + + def set_version(self, v): + self.version = 1 + self.redeemscript = self.redeemscript_v1 + + +class ContractManager: + """A device that spends from a Mecenas Contract in two different ways.""" + def __init__(self, contract_tuple_list, keypairs, public_keys, wallet): + self.contract_tuple_list = contract_tuple_list + self.contract_index=0 + self.chosen_utxo = 0 + self.sequence = 0 + self.txin = dict() + self.keypair = keypairs + self.pubkeys = public_keys + self.wallet = wallet + + if len(self.contract_tuple_list): + self.choice(self.contract_tuple_list[0], 0, 0) + + def choice(self, contract_tuple, utxo_index, m): + self.tx = contract_tuple[UTXO][utxo_index] + self.contract = contract_tuple[CONTRACT] + self.mode = m + self.dummy_scriptsig = '00'*(110 + len(self.contract.redeemscript)) + self.version = self.contract.version + self.script_pub_key = Script.P2SH_script(self.contract.address.hash160).hex() + self.value = int(self.tx.get('value')) + + self.txin=[] + self.chosen_utxo=utxo_index + self.contract_index = self.contract_tuple_list.index(contract_tuple) + + self.sequence = 0 + + utxo = contract_tuple[UTXO][utxo_index] + + self.value = int(utxo.get('value')) + self.txin = [dict( + prevout_hash=utxo.get('tx_hash'), + prevout_n=int(utxo.get('tx_pos')), + # sequence=self.sequence, + scriptSig=self.dummy_scriptsig, + type='unknown', + address=self.contract.address, + scriptCode=self.contract.redeemscript.hex(), + num_sig=1, + signatures=[None], + x_pubkeys=[self.pubkeys[self.contract_index][self.mode]], + value=int(utxo.get('value')), + )] + + def complete_method(self, action='default'): + return self.complete + + def signtx(self, tx): + """generic tx signer for compressed pubkey""" + tx.sign(self.keypair) + + def complete(self, tx): + """ + Completes transaction by creating scriptSig. You need to sign the + transaction before using this (see `signtx`). + This works on multiple utxos if needed. + """ + pub = bytes.fromhex(self.pubkeys[self.contract_index][self.mode]) + for txin in tx.inputs(): + # find matching inputs + if txin['address'] != self.contract.address: + continue + sig = txin['signatures'][0] + if not sig: + continue + sig = bytes.fromhex(sig) + + if txin['scriptSig'] == self.dummy_scriptsig: + script = [ + Script.push_data(sig), + Script.push_data(pub), + Script.push_data(self.contract.redeemscript) + ] + # print("scriptSig length " + str(joinbytes(script).hex().__sizeof__())) + txin['scriptSig'] = joinbytes(script).hex() + # need to update the raw, otherwise weird stuff happens. + tx.raw = tx.serialize() + + def spend_tx(self, inputs): + """ + Prepares a raw unsigned transaction to spend smart contract + Inputs are provided as parameter + Output is a P2PKH address specified (commonly random) upon contract creation + Fee is calculated with a target of 1 sat/byte + """ + outputs = [ + (TYPE_ADDRESS, self.contract.addresses[SELF], self.value)] + + tx = Transaction.from_io(inputs, outputs, locktime=self.contract.i_time) + tx.version = 2 + fee = (len(tx.serialize(True)) // 2 + 1) + if fee > self.value: + raise Exception("Not enough funds to make the transaction!") + outputs = [ + (TYPE_ADDRESS, self.contract.addresses[SELF], self.value - fee)] + tx = Transaction.from_io(inputs, outputs, locktime=self.contract.i_time) + tx.version = 2 + return tx diff --git a/hodl/qt.py b/hodl/qt.py new file mode 100755 index 0000000..b9ed379 --- /dev/null +++ b/hodl/qt.py @@ -0,0 +1,183 @@ +from PyQt5 import QtGui +from PyQt5 import QtCore +from PyQt5.QtCore import * + +import electroncash.version +from electroncash.i18n import _ +from electroncash.plugins import BasePlugin, hook +from electroncash_gui.qt.util import destroyed_print_error +from electroncash.util import finalization_print_error + + + +class Timer(QObject): + update_sig = pyqtSignal() + + def __init__(self, parent, window, widget): + super().__init__(parent=parent) + + self.window = window + self.widget = widget + self.update_sig.connect(self.on_update) + self.timer = QTimer(self) + self.timer.setSingleShot(True) + self.timer.setInterval(2500) + self.timer.timeout.connect(self.update_sig) + + def on_update(self): + if not self.window.network or not self.window.network.is_connected(): + return + + self.widget.rescan_contracts() + +class Plugin(BasePlugin): + electrumcash_qt_gui = None + # There's no real user-friendly way to enforce this. So for now, we just calculate it, and ignore it. + is_version_compatible = True + + def __init__(self, parent, config, name): + BasePlugin.__init__(self, parent, config, name) + self.network=None + self.wallet_windows = {} + self.hodl_tabs = {} + self.hodl_tab= {} + self.timers = {} + + def fullname(self): + return 'HODL' + + def diagnostic_name(self): + return "HODL" + + def description(self): + return _("HODL Plugin") + + def on_close(self): + """ + BasePlugin callback called when the wallet is disabled among other things. + """ + for window in list(self.wallet_windows.values()): + self.close_wallet(window.wallet) + + @hook + def balance_label_extra(self, window): + wallet_name = window.wallet.basename() + if self.timers[wallet_name].timer: + self.timers[wallet_name].timer.stop() + self.timers[wallet_name].timer.start() + + @hook + def update_contact(self, address, new_entry, old_entry): + print("update_contact", address, new_entry, old_entry) + + @hook + def delete_contacts(self, contact_entries): + print("delete_contacts", contact_entries) + + @hook + def init_qt(self, qt_gui): + """ + Hook called when a plugin is loaded (or enabled). + """ + self.electrumcash_qt_gui = qt_gui + # We get this multiple times. Only handle it once, if unhandled. + if len(self.wallet_windows): + return + # These are per-wallet windows. + for window in self.electrumcash_qt_gui.windows: + self.load_wallet(window.wallet, window) + + @hook + def load_wallet(self, wallet, window): + """ + Hook called when a wallet is loaded and a window opened for it. + """ + wallet_name = window.wallet.basename() + self.wallet_windows[wallet_name] = window + self.add_ui_for_wallet(wallet_name, window) + self.refresh_ui_for_wallet(wallet_name) + + @hook + def close_wallet(self, wallet): + + wallet_name = wallet.basename() + window = self.wallet_windows[wallet_name] + del self.wallet_windows[wallet_name] + self.remove_ui_for_wallet(wallet_name, window) + + @staticmethod + def _get_icon() -> QtGui.QIcon: + import os + path = os.path.dirname(os.path.abspath(__file__)) + if ".zip" in path: + import zipfile + zip_path = os.path.split(path)[0] + zip_dir = os.path.split(zip_path)[0] + unzip_path = os.path.join(zip_dir, 'hodl') + with zipfile.ZipFile(zip_path, 'r') as zip_ref: + zip_ref.extract("icons.rcc", unzip_path) + rcpath = os.path.join(unzip_path,"icons.rcc") + else: + rcpath = os.path.join(path, "..", "icons.rcc") + QtCore.QResource.registerResource(rcpath) + icon = QtGui.QIcon(":/diamond.png") + return icon + + def add_ui_for_wallet(self, wallet_name, window): + from .ui import Manage + widget = Manage(window, self, wallet_name, password=None, manager=None) + tab = window.create_list_tab(widget) + self.hodl_tabs[wallet_name] = tab + self.hodl_tab[wallet_name] = widget + window.tabs.addTab(tab, self._get_icon(), _('HODL')) + self.timers[wallet_name] = Timer(None, window, widget) + + def remove_ui_for_wallet(self, wallet_name, window): + wallet_tab = self.hodl_tabs.get(wallet_name, None) + widget = self.hodl_tab.get(wallet_name) + if wallet_tab is not None: + if widget and callable(getattr(widget, 'kill_join', None)): + widget.kill_join() # kill thread, wait for up to 2.5 seconds for it to exit + if widget and callable(getattr(widget, 'clean_up', None)): + widget.clean_up() # clean up wallet and stop its threads + del self.hodl_tab[wallet_name] + del self.hodl_tabs[wallet_name] + if wallet_tab: + i = window.tabs.indexOf(wallet_tab) + window.tabs.removeTab(i) + wallet_tab.deleteLater() + self.print_error("Removed UI for", wallet_name) + self.timers[wallet_name].timer.stop() + del self.timers[wallet_name] + + + def refresh_ui_for_wallet(self, wallet_name): + wallet_tab = self.hodl_tabs.get(wallet_name) + if wallet_tab: + wallet_tab.update() + wallet_tab = self.hodl_tab.get(wallet_name) + if wallet_tab: + wallet_tab.update() + + def switch_to(self, mode, wallet_name, password, manager): + window=self.wallet_windows[wallet_name] + try: + l = mode(window, self, wallet_name, password=password, manager=manager) + tab = window.create_list_tab(l) + destroyed_print_error(tab) # track object lifecycle + finalization_print_error(tab) # track object lifecycle + + old_tab = self.hodl_tabs.get(wallet_name, None) + i = window.tabs.indexOf(old_tab) + + self.hodl_tabs[wallet_name] = tab + self.hodl_tab[wallet_name] = l + if old_tab: + window.tabs.removeTab(i) + old_tab.searchable_list.deleteLater() + old_tab.deleteLater() + window.tabs.insertTab(i,tab, self._get_icon(), _('HODL')) + window.tabs.setCurrentIndex(i) + except Exception as e: + self.print_error(repr(e)) + return diff --git a/hodl/ui.py b/hodl/ui.py new file mode 100755 index 0000000..5d03a43 --- /dev/null +++ b/hodl/ui.py @@ -0,0 +1,468 @@ +from PyQt5.QtCore import * +from PyQt5.QtGui import * +from PyQt5.QtWidgets import * + +import electroncash.web as web +import webbrowser +from .hodl_contract import HodlContract, LOCKTIME_THRESHOLD +from electroncash.address import ScriptOutput, OpCodes, Address, Script +from electroncash.transaction import Transaction,TYPE_ADDRESS, TYPE_SCRIPT, SerializationError +from electroncash_gui.qt.amountedit import BTCAmountEdit +from electroncash.i18n import _ +from electroncash_gui.qt.util import * +from electroncash.wallet import Multisig_Wallet, ImportedPrivkeyWallet, Standard_Wallet +from electroncash.util import NotEnoughFunds, ServerErrorResponse +from electroncash_gui.qt.transaction_dialog import show_transaction + +from .contract_finder import find_contract_in_wallet +from .hodl_contract import ContractManager, UTXO, CONTRACT +from .util import * +from math import ceil +import json +import datetime + +class AdvancedWid(QWidget): + toggle_sig = pyqtSignal() + def __init__(self, parent): + QWidget.__init__(self, parent) + vbox = QVBoxLayout(self) + hbox = QHBoxLayout() + l = QLabel(" %s " % "Lock options") + vbox.addWidget(l) + self.block_height_edit = QLineEdit() + self.block_height_edit.setPlaceholderText("Block height") + self.block_height_radio = QRadioButton("Until block height: ") + self.block_height_radio.option = 1 + self.block_height_radio.setChecked(True) + self.block_height_radio.toggled.connect(self.onClick) + self.block_height_edit.setDisabled(False) + currentHeight = parent.main_window.network.get_local_height() + self.block_height_edit.setText(str(currentHeight)) + self.block_height_edit.setValidator(QIntValidator(0, 500000000, self)) + self.block_height_edit.setFixedWidth(134) + + def reject(): + try: + val = int(self.block_height_edit.text()) + except: + val = 0 + self.block_height_edit.setText("0" if val < 0 else "500000000" if val > 500000000 else "0") + + self.block_height_edit.inputRejected.connect(reject) + self.block_height_edit.textEdited.connect(self.toggle_sig.emit) + vbox.addLayout(hbox) + hbox.addWidget(self.block_height_radio) + hbox.addWidget(self.block_height_edit) + hbox.addStretch(1) + + hbox2 = QHBoxLayout() + self.date_radio = QRadioButton("Until calendar date:") + self.date_radio.option = 2 + self.date_edit = QDateTimeEdit(calendarPopup=True) + self.date_edit.setDateTime(QDateTime.currentDateTime()) + self.date_edit.setDisabled(True) + self.date_edit.dateTimeChanged.connect(self.toggle_sig.emit) + vbox.addLayout(hbox2) + hbox2.addWidget(self.date_radio) + hbox2.addWidget(self.date_edit) + hbox2.addStretch(1) + + self.date_radio.toggled.connect(self.onClick) + + self.option = 1 + + def onClick(self): + radio = self.sender() + self.option = radio.option + self.block_height_edit.setDisabled(not self.block_height_radio.isChecked()) + self.date_edit.setDisabled(not self.date_radio.isChecked()) + self.toggle_sig.emit() + + + +class Create(QDialog, MessageBoxMixin): + + def __init__(self, parent, plugin, wallet_name, password): + QDialog.__init__(self, parent) + self.main_window = parent + self.wallet = parent.wallet + self.plugin = plugin + self.wallet_name = wallet_name + self.config = parent.config + self.password = password + self.contract = None + self.version = 1 + self.fund_domain = None + self.fund_change_address = None + self.redeem_address = self.wallet.get_unused_address() + self.block_height = None + self.addresses = [] + self.cashaccounts = self.wallet.cashacct.get_wallet_cashaccounts() + self.my_addresses = dict() + for i in self.cashaccounts: + self.my_addresses[i.name + '#' + str(i.number)] = i.address + self.my_addresses["new random address"] = self.wallet.get_unused_address() + self.my_addresses_combo = QComboBox() + self.my_addresses_combo.addItems(list(self.my_addresses.keys())) + self.my_addresses_combo.currentIndexChanged.connect(self.contract_info_changed) + + vbox = QVBoxLayout() + self.setLayout(vbox) + hbox = QHBoxLayout() + vbox.addLayout(hbox) + l = QLabel("%s" % (_("Creating new HODL contract:"))) + hbox.addWidget(l) + + l = QLabel(_("Redeem address") + ":") + hbox = QHBoxLayout() + vbox.addLayout(hbox) + hbox.addWidget(l) + hbox.addWidget(self.my_addresses_combo) + hbox.addStretch(1) + + l = QLabel(_("Value to lock: ")) + hbox = QHBoxLayout() + vbox.addLayout(hbox) + hbox.addWidget(l) + + self.locked_value_edit = BTCAmountEdit(self.main_window.get_decimal_point) + self.locked_value_edit.setAmount(1000000) + self.locked_value_edit.setFixedWidth(155) + self.locked_value_edit.textEdited.connect(self.contract_info_changed) + hbox.addWidget(self.locked_value_edit) + hbox.addStretch(1) + + self.advanced_wid = AdvancedWid(self) + self.advanced_wid.toggle_sig.connect(self.contract_info_changed) + vbox.addWidget(self.advanced_wid) + b = QPushButton(_("Create HODL Contract")) + b.clicked.connect(self.create_contract) + vbox.addStretch(1) + vbox.addWidget(b) + self.create_button = b + self.create_button.setDisabled(False) + vbox.addStretch(1) + + # initialize default contract + self.contract_info_changed() + + + def contract_info_changed(self, ): + # if any of the txid/out#/value changes + try: + try: + val = int(self.locked_value_edit.get_amount()) + except: + val = 0 + if val < 1000: + self.locked_value_edit.setAmount(1000) + + self.redeem_address = list(self.my_addresses.values())[self.my_addresses_combo.currentIndex()] + self.locked_value = self.locked_value_edit.get_amount() + self.block_height = int(self.advanced_wid.block_height_edit.text()) + + dtime = self.advanced_wid.date_edit.dateTime().toPyDateTime() + self.lock_date = int(dtime.timestamp()) + self.i_time = self.block_height if self.advanced_wid.option == 1 else self.lock_date + + self.version = 1 + self.addresses = [self.redeem_address] + + except Exception as e: + self.create_button.setDisabled(True) + print(e) + else: + self.create_button.setDisabled(False) + self.contract = HodlContract(self.addresses, v=self.version, data=[self.i_time, self.locked_value]) + + + def build_otputs(self): + outputs = [] + outputs.append((TYPE_SCRIPT, ScriptOutput(self.contract.op_return),0)) + for a in self.addresses: + outputs.append((TYPE_ADDRESS, a, 546)) + outputs.append((TYPE_ADDRESS, self.contract.address, self.locked_value)) + return outputs + + + def create_contract(self, ): + yorn = self.main_window.question(_( + "Do you wish to create the HODL Contract?")) + if not yorn: + return + outputs = self.build_otputs() + try: + tx = self.wallet.mktx(outputs, self.password, self.config, + domain=self.fund_domain, change_addr=self.fund_change_address) + except NotEnoughFunds: + return self.show_critical(_("Not enough balance to fund smart contract.")) + except Exception as e: + return self.show_critical(repr(e)) + try: + self.create_button.setText("Creating HODL Contract...") + self.create_button.setDisabled(True) + self.main_window.network.broadcast_transaction2(tx) + #show_transaction(tx, self.main_window, "Create Contract", prompt_if_unsaved=True) + except Exception as e: + print(e, tx) + return self.show_critical(repr(e)) + + self.accept() + + +class ContractTree(MessageBoxMixin, PrintError, MyTreeWidget): + update_sig = pyqtSignal() + + def __init__(self, parent, contracts): + MyTreeWidget.__init__(self, parent, self.create_menu,[ + _('Contract address'), + _('Unlocked in: '), + _('Amount'), + ],stretch_column=0, deferred_updates=True) + self.contracts = contracts + self.monospace_font = QFont(MONOSPACE_FONT) + + self.main_window = parent + self.setSelectionMode(QAbstractItemView.SingleSelection) + self.setSortingEnabled(True) + self.update_sig.connect(self.on_update) + self.timer = QTimer(self) + self.timer.setSingleShot(False) + self.timer.timeout.connect(self.update_sig) + self.timer.start(10000) + self.setEditTriggers(QTreeWidget.NoEditTriggers) + self.setExpandsOnDoubleClick(False) + self.editable_columns = [] + + def create_menu(self, position): + pass + + def get_selected_id(self): + if self.currentItem() == None: + return None, None + + utxo = self.currentItem().data(0, Qt.UserRole) + contract = self.currentItem().data(1, Qt.UserRole) + if utxo == None: + index = -1 + else: + index = contract[UTXO].index(utxo) + return contract, index + + def on_doubleclick(self): + contract, _ = self.get_selected_id() + tx_hash = contract[UTXO][0]['tx_hash'] + + for hash, t in self.parent.wallet.transactions.items(): + if hash == tx_hash: + self.main_window.show_transaction(t) + + + def on_update(self): + selectedContract, _ = self.get_selected_id() + self.clear() + + for contract in self.contracts: + utxo = contract[UTXO][0] + + expiration = self.estimate_expiration(utxo, contract) + amount = self.parent.format_amount(utxo.get('value'), is_diff=False, whitespaces=True) + item = QTreeWidgetItem([contract[CONTRACT].address.to_ui_string(), expiration, amount]) + item.setData(0, Qt.UserRole, utxo) + item.setData(1, Qt.UserRole, contract) + + self.addChild(item) + if contract == selectedContract: + self.setCurrentItem(item) + + def estimate_expiration(self, utxo, contract): + """estimates age of the utxo in days. There are 144 blocks per day on average""" + + contract_i_time=contract[CONTRACT].i_time + if contract_i_time > 500000000: + # timestamp + now = int(datetime.datetime.now().timestamp()) + print(contract_i_time, now, contract_i_time - now) + if contract_i_time - now >= 0: + if (contract_i_time - now)/86400 > 1.: + return '{0:.1f}'.format((contract_i_time - now)/86400) + " days" + if (contract_i_time - now)/3600 > 1.: + return '~{0}'.format(round((contract_i_time - now)/3600)) + " hours" + if (contract_i_time - now)/60 > 1.: + return '~{0}'.format(round((contract_i_time - now)/60)) + " minutes" + + return '{0}'.format(contract_i_time - now) + " seconds" + else: + # block height + currentHeight = self.main_window.network.get_local_height() + if contract_i_time - currentHeight > 0: + return str(contract_i_time - currentHeight) + " blocks" + + return _("Unlocked") + +class Manage(QWidget, MessageBoxMixin): + def __init__(self, parent, plugin, wallet_name, password, manager): + QWidget.__init__(self, parent) + self.password=password + + self.main_window = parent + self.wallet=parent.wallet + self.plugin = plugin + self.wallet_name = wallet_name + self.config = parent.config + self.manager = manager + + self.first_paint = True + self.second_paint = True + + self.contracts = [] + + vbox = QVBoxLayout() + self.setLayout(vbox) + try: + self.contract_tree = ContractTree(self.main_window, self.contracts) + self.contract_tree.on_update() + vbox.addWidget(self.contract_tree) + hbox = QHBoxLayout() + vbox.addStretch(1) + hbox = QHBoxLayout() + vbox.addLayout(hbox) + b = QPushButton(_("Create new HODL Contract")) + b.clicked.connect(self.show_create_contract) + hbox.addWidget(b) + + self.spend_button = QPushButton(_("Spend contract")) + self.spend_button.clicked.connect(self.spend) + hbox.addWidget(self.spend_button) + + self.contract_tree.currentItemChanged.connect(self.update_buttons) + self.update_buttons() + except Exception as ex: + print(ex) + import sys + trace_back = sys.exc_info()[2] + line = trace_back.tb_lineno + # raise FlowException("Process Exception in line {}".format(line), e) + print(trace_back, trace_back.tb_lineno) + + raise ex + + def paintEvent(self, event): + if self.first_paint: + self.first_paint = False + + if not isinstance(self.wallet, (Standard_Wallet)): + self.main_window.show_error( + "This plugin is designed for standard HD wallets only") + + return + + if self.second_paint: + self.second_paint = False + + if not self.manager: + self.rescan_contracts() + else: + self.contracts = self.manager.contract_tuple_list + self.contract_tree.contracts = self.contracts + self.contract_tree.on_update() + + def show_create_contract(self): + if not self.prompt_password(): + return + Create(self.main_window, self.plugin, self.wallet_name, self.password).exec() + + def update_buttons(self): + contract, utxo_index = self.contract_tree.get_selected_id() + if not contract: + self.spend_button.setDisabled(True) + return + + self.spend_button.setDisabled(False) + + def prompt_password(self): + if self.wallet.has_password(): + if not self.password: + self.password = self.main_window.password_dialog() + if not self.password: + return False + try: + self.wallet.keystore.get_private_key((True,0), self.password) + except Exception as e: + self.show_error("Wrong password.") + self.password = None + return False + + return True + + def spend(self): + yorn=self.main_window.question(_("Do you wish to spend this contract?")) + if yorn: + try: + if not self.prompt_password(): + return + keypairs, public_keys = self.get_keypairs_for_contracts(self.contracts) + self.manager = ContractManager(self.contracts, keypairs, public_keys, self.wallet) + + contract, utxo_index = self.contract_tree.get_selected_id() + self.manager.choice(contract, utxo_index, 0) + inputs = self.manager.txin + tx = self.manager.spend_tx(inputs) + complete = self.manager.complete_method() + if not self.wallet.is_watching_only(): + self.manager.signtx(tx) + complete(tx) + self.main_window.network.broadcast_transaction2(tx) + except ServerErrorResponse as e: + bip68msg = 'the transaction was rejected by network rules.\n\nnon-BIP68-final (code 64)' + locktimeMsg = 'Locktime requirement not satisfied' + nonFinalMsg = 'non-final' + print(e.server_msg) + + if any(msg in e.server_msg['message'] for msg in [bip68msg, locktimeMsg, nonFinalMsg]): + contract_i_time = contract[CONTRACT].i_time + now = int(datetime.datetime.now().timestamp()) + if contract[CONTRACT].i_time > LOCKTIME_THRESHOLD and contract_i_time - now < 0: + self.show_error("Not ready yet!\nAllow for extra time (up to 70 minutes) for the date based timelock transaction to be accepted by the network") + else: + self.show_error("Not ready yet!") + else: + self.show_error(e.server_msg) + except Exception as e: + self.show_error(e) + + def rescan_contracts(self): + self.find_contracts() + self.contract_tree.contracts = self.contracts + self.contract_tree.on_update() + + def find_contracts(self): + self.contracts = find_contract_in_wallet(self.wallet, HodlContract) + + def get_keypairs_for_contracts(self, contract_tuple_list): + keypairs = dict() + public_keys=[] + + if not len(contract_tuple_list): + return keypairs, public_keys + + for t in contract_tuple_list: + public_keys.append(dict()) + for m in [0]: + my_address=t[CONTRACT].addresses[m] + i = self.wallet.get_address_index(my_address) + if not self.wallet.is_watching_only(): + priv = self.wallet.keystore.get_private_key(i, self.password) + else: + print("watch only") + priv = None + try: + if isinstance(self.wallet, ImportedPrivkeyWallet): + public = [self.wallet.keystore.address_to_pubkey(my_address).to_ui_string()] + else: + public = self.wallet.get_public_keys(my_address) + public_keys[contract_tuple_list.index(t)][m]=public[0] + keypairs[public[0]] = priv + except Exception as ex: + print(ex) + return keypairs, public_keys diff --git a/hodl/util.py b/hodl/util.py new file mode 100755 index 0000000..2ac2799 --- /dev/null +++ b/hodl/util.py @@ -0,0 +1,20 @@ +from electroncash.address import OpCodes +import time + + +EXPIRY =time.strptime("1 08 2020", "%d %m %Y") + +def make_opreturn(data): + """Turn data bytes into a single-push opreturn script""" + if len(data) < 76: + return bytes((OpCodes.OP_RETURN, len(data))) + data + elif len(data) < 256: + return bytes((OpCodes.OP_RETURN, 76, len(data))) + data + else: + raise ValueError(data) + + +def is_expired(): + now=time.localtime(time.time()) + return EXPIRY + + diamond.png + + diff --git a/icons.rcc b/icons.rcc new file mode 100644 index 0000000..c910a5f Binary files /dev/null and b/icons.rcc differ diff --git a/manifest.json b/manifest.json new file mode 100755 index 0000000..933e2ff --- /dev/null +++ b/manifest.json @@ -0,0 +1,11 @@ +{ + "display_name": "HODL", + "version": "1.0.0", + "description": "Lock your funds and have no FUD", + "project_url": "https://github.com/mainnet-pat/hodl_ec_plugin", + "minimum_ec_version": "4.2.0", + "package_name": "hodl", + "available_for": [ + "qt" + ] +} diff --git a/pack.sh b/pack.sh new file mode 100755 index 0000000..a035390 --- /dev/null +++ b/pack.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +pushd "$(dirname ${BASH_SOURCE[0]})" + +rm hodl.v*.zip +rm -rf hodl/__pycache__ +zip -r -X hodl.v1.0.0.zip hodl/ pictures/ diamond.png hodl.cash icons.* LICENSE manifest.json README.md + +popd \ No newline at end of file diff --git a/pictures/add_plugin.png b/pictures/add_plugin.png new file mode 100755 index 0000000..7e56417 Binary files /dev/null and b/pictures/add_plugin.png differ diff --git a/pictures/donate.png b/pictures/donate.png new file mode 100644 index 0000000..bb1cb16 Binary files /dev/null and b/pictures/donate.png differ diff --git a/pictures/installing.png b/pictures/installing.png new file mode 100755 index 0000000..1014e1f Binary files /dev/null and b/pictures/installing.png differ diff --git a/pictures/logo.png b/pictures/logo.png new file mode 100644 index 0000000..5ed611a Binary files /dev/null and b/pictures/logo.png differ