[
  {
    "path": ".gitignore",
    "content": "vendor\ncomposer.lock\n.idea\n"
  },
  {
    "path": "LICENSE",
    "content": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<http://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this\nlicense document, but changing it is not allowed.\n\n### Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom\nto share and change all versions of a program--to make sure it remains\nfree software for all its users. We, the Free Software Foundation, use\nthe GNU General Public License for most of our software; it applies\nalso to any other work released this way by its authors. You can apply\nit to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you\nhave certain responsibilities if you distribute copies of the\nsoftware, or if you modify it: responsibilities to respect the freedom\nof others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the\nmanufacturer can do so. This is fundamentally incompatible with the\naim of protecting users' freedom to change the software. The\nsystematic pattern of such abuse occurs in the area of products for\nindividuals to use, which is precisely where it is most unacceptable.\nTherefore, we have designed this version of the GPL to prohibit the\npractice for those products. If such problems arise substantially in\nother domains, we stand ready to extend this provision to those\ndomains in future versions of the GPL, as needed to protect the\nfreedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish\nto avoid the special danger that patents applied to a free program\ncould make it effectively proprietary. To prevent this, the GPL\nassures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n### TERMS AND CONDITIONS\n\n#### 0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds\nof works, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of\nan exact copy. The resulting work is called a \"modified version\" of\nthe earlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user\nthrough a computer network, with no transfer of a copy, is not\nconveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\" to\nthe extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n#### 1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work for\nmaking modifications to it. \"Object code\" means any non-source form of\na work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can\nregenerate automatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same\nwork.\n\n#### 2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey,\nwithout conditions so long as your license otherwise remains in force.\nYou may convey covered works to others for the sole purpose of having\nthem make modifications exclusively for you, or provide you with\nfacilities for running those works, provided that you comply with the\nterms of this License in conveying all material for which you do not\ncontrol copyright. Those thus making or running the covered works for\nyou must do so exclusively on your behalf, under your direction and\ncontrol, on terms that prohibit them from making any copies of your\ncopyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the\nconditions stated below. Sublicensing is not allowed; section 10 makes\nit unnecessary.\n\n#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such\ncircumvention is effected by exercising rights under this License with\nrespect to the covered work, and you disclaim any intention to limit\noperation or modification of the work as a means of enforcing, against\nthe work's users, your or third parties' legal rights to forbid\ncircumvention of technological measures.\n\n#### 4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n#### 5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these\nconditions:\n\n-   a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n-   b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under\n    section 7. This requirement modifies the requirement in section 4\n    to \"keep intact all notices\".\n-   c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy. This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged. This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n-   d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n#### 6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms of\nsections 4 and 5, provided that you also convey the machine-readable\nCorresponding Source under the terms of this License, in one of these\nways:\n\n-   a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n-   b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the Corresponding\n    Source from a network server at no charge.\n-   c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source. This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n-   d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge. You need not require recipients to copy the\n    Corresponding Source along with the object code. If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source. Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n-   e) Convey the object code using peer-to-peer transmission,\n    provided you inform other peers where the object code and\n    Corresponding Source of the work are being offered to the general\n    public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal,\nfamily, or household purposes, or (2) anything designed or sold for\nincorporation into a dwelling. In determining whether a product is a\nconsumer product, doubtful cases shall be resolved in favor of\ncoverage. For a particular product received by a particular user,\n\"normally used\" refers to a typical or common use of that class of\nproduct, regardless of the status of the particular user or of the way\nin which the particular user actually uses, or expects or is expected\nto use, the product. A product is a consumer product regardless of\nwhether the product has substantial commercial, industrial or\nnon-consumer uses, unless such uses represent the only significant\nmode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to\ninstall and execute modified versions of a covered work in that User\nProduct from a modified version of its Corresponding Source. The\ninformation must suffice to ensure that the continued functioning of\nthe modified object code is in no case prevented or interfered with\nsolely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or\nupdates for a work that has been modified or installed by the\nrecipient, or for the User Product in which it has been modified or\ninstalled. Access to a network may be denied when the modification\nitself materially and adversely affects the operation of the network\nor violates the rules and protocols for communication across the\nnetwork.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n#### 7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders\nof that material) supplement the terms of this License with terms:\n\n-   a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n-   b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n-   c) Prohibiting misrepresentation of the origin of that material,\n    or requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n-   d) Limiting the use for publicity purposes of names of licensors\n    or authors of the material; or\n-   e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n-   f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions\n    of it) with contractual assumptions of liability to the recipient,\n    for any liability that these contractual assumptions directly\n    impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions; the\nabove requirements apply either way.\n\n#### 8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your license\nfrom a particular copyright holder is reinstated (a) provisionally,\nunless and until the copyright holder explicitly and finally\nterminates your license, and (b) permanently, if the copyright holder\nfails to notify you of the violation by some reasonable means prior to\n60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n#### 9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or run\na copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n#### 10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n#### 11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims owned\nor controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within the\nscope of its coverage, prohibits the exercise of, or is conditioned on\nthe non-exercise of one or more of the rights that are specifically\ngranted under this License. You may not convey a covered work if you\nare a party to an arrangement with a third party that is in the\nbusiness of distributing software, under which you make payment to the\nthird party based on the extent of your activity of conveying the\nwork, and under which the third party grants, to any of the parties\nwho would receive the covered work from you, a discriminatory patent\nlicense (a) in connection with copies of the covered work conveyed by\nyou (or copies made from those copies), or (b) primarily for and in\nconnection with specific products or compilations that contain the\ncovered work, unless you entered into that arrangement, or that patent\nlicense was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n#### 12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under\nthis License and any other pertinent obligations, then as a\nconsequence you may not convey it at all. For example, if you agree to\nterms that obligate you to collect a royalty for further conveying\nfrom those to whom you convey the Program, the only way you could\nsatisfy both those terms and this License would be to refrain entirely\nfrom conveying the Program.\n\n#### 13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n#### 14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions\nof the GNU General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in\ndetail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program\nspecifies that a certain numbered version of the GNU General Public\nLicense \"or any later version\" applies to it, you have the option of\nfollowing the terms and conditions either of that numbered version or\nof any later version published by the Free Software Foundation. If the\nProgram does not specify a version number of the GNU General Public\nLicense, you may choose any version ever published by the Free\nSoftware Foundation.\n\nIf the Program specifies that a proxy can decide which future versions\nof the GNU General Public License can be used, that proxy's public\nstatement of acceptance of a version permanently authorizes you to\nchoose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n#### 15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT\nWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND\nPERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\nDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR\nCORRECTION.\n\n#### 16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR\nCONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES\nARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT\nNOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR\nLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM\nTO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n#### 17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\n### How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these\nterms.\n\nTo do so, attach the following notices to the program. It is safest to\nattach them to the start of each source file to most effectively state\nthe exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n        <one line to give the program's name and a brief idea of what it does.>\n        Copyright (C) <year>  <name of author>\n\n        This program is free software: you can redistribute it and/or modify\n        it under the terms of the GNU General Public License as published by\n        the Free Software Foundation, either version 3 of the License, or\n        (at your option) any later version.\n\n        This program is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n        GNU General Public License for more details.\n\n        You should have received a copy of the GNU General Public License\n        along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper\nmail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n        <program>  Copyright (C) <year>  <name of author>\n        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n        This is free software, and you are welcome to redistribute it\n        under certain conditions; type `show c' for details.\n\nThe hypothetical commands \\`show w' and \\`show c' should show the\nappropriate parts of the General Public License. Of course, your\nprogram's commands might be different; for a GUI interface, you would\nuse an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary. For more information on this, and how to apply and follow\nthe GNU GPL, see <http://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your\nprogram into proprietary programs. If your program is a subroutine\nlibrary, you may consider it more useful to permit linking proprietary\napplications with the library. If this is what you want to do, use the\nGNU Lesser General Public License instead of this License. But first,\nplease read <http://www.gnu.org/philosophy/why-not-lgpl.html>."
  },
  {
    "path": "README.md",
    "content": "**This project is now archived.**\n\nThis tool _does_ work for importing blockchain data in to Neo4j, but it's **very slow**.\n\nIt imports each block and transaction individually, and there's so much data that it will take years to get up to date with the current tip of the blockchain (if ever).\n\nI haven't got the time to maintain this project, so that's why I'm archiving it. However, if you want to create your own (faster) tool, I've written a guide on [how to import Bitcoin in to Neo4j](docs/how.md) that you may find helpful.\n\n-----\n\n# Bitcoin to Neo4j\n\n![](docs/images/splash.png)\n\n_See the [cypher examples](docs/cypher.md) for cool screenshots._\n\n## Summary.\n\nThis script _runs through_ a **bitcoin blockchain** and inserts it in to a **Neo4j graph database**.\n\nI use this script to power my bitcoin blockchain browser: <http://learnmeabitcoin.com/browser> \n\n**Important:**\n\n* **The resulting Neo4j database is roughly _6x_ the size of the blockchain.** So if the blockchain is 100GB, your Neo4j database will be **600GB**.\n* **It may take 60+ days to finish importing the entire blockchain.** Instead of doing a bulk import of the entire blockchain, this script runs through each `blk.dat`<sup>[1](#blkdat)</sup> file and inserts each block and transaction it encounters. So whilst it takes \"a while\" for an initial import, when it's complete it will continuously add new blocks as they arrive.\n\nNonetheless, you can still [browse](docs/cypher.md) whatever is in the database whilst this script is running.\n\n## Install.\n\nI have only used this on **Linux (Ubuntu)**.\n\nIt should work on OSX and Windows, but I haven't got installation instructions for those.\n\n### Software.\n\nThis script makes use of the following software: \n\n1. **[Bitcoin Core](https://bitcoin.org/en/download)**\n\n```bash\nsudo add-apt-repository ppa:bitcoin/bitcoin\nsudo apt update\nsudo apt install bitcoind\n```\n\n2. **[Neo4j 4.0+](https://neo4j.com/)**\n\n```bash\nsudo add-apt-repository ppa:webupd8team/java\nsudo apt update\nsudo apt install oracle-java8-installer\n\nwget -O - https://debian.neo4j.org/neotechnology.gpg.key | sudo apt-key add -\necho 'deb https://debian.neo4j.org/repo stable/' | sudo tee /etc/apt/sources.list.d/neo4j.list\nsudo apt update && sudo apt install neo4j\n```\n\n3. **[PHP 8.0+](http://php.net/)** - The main script and it's library functions are written in PHP.\n\n```bash\n# The following php-* libraries are required for this script to run\nsudo apt install php php-dev php-gmp php-curl php-bcmath php-mbstring\n```\n\n4. **[Redis 5.0.3+](https://redis.io/)** - This is used for storing the state of the import, so that the script can be stopped and started at any time.\n\n```bash\nsudo apt install build-essential\nsudo apt install redis-server\n```\n\n### Dependencies.\n\n**1. [neo4j-php-client](https://github.com/neo4j-php/neo4j-php-client)** (install via [composer](https://getcomposer.org/doc/00-intro.md)).\n\nThis is the driver that allows PHP to connect to your Neo4j database. I have included a `composer.json` file, so navigate to the project's home directory and install it with:\n\n```bash\ncomposer install\n```\n\n**2. [phpredis](https://github.com/phpredis/phpredis)**\n\nThis allows PHP to connect to Redis. These instructions should install the version needed for _PHP7_ (which is different to the default installation instructions that come with phpredis, which is aimed at PHP5).\n\n```bash\n# Install phpredis\nsudo apt install php-redis\n```\n\n### Config.\n\nThe `config.php` file contains all the configuration settings. You probably only need to change:\n\n1. The location of your `~/.bitcoin/blocks` folder \n2. Your Neo4j username and password.\n\n```php\ndefine(\"BLOCKS\", '/home/user/.bitcoin/blocks'); // the location of the blk.dat files you want to read\ndefine(\"TESTNET\", false); // are you reading blk.dat files from Bitcoin's testnet?\n\ndefine(\"NEO4J_USER\", 'neo4j');\ndefine(\"NEO4J_PASS\", 'neo4j');\ndefine(\"NEO4J_IP\", 'localhost');    \ndefine(\"NEO4J_PORT\", '7687'); // this is the port used for the bolt protocol\n\ndefine(\"REDIS_IP\", 'localhost');    \ndefine(\"REDIS_PORT\", '6379');\n\n```\n\n## Run.\n\nMake sure Neo4j is running (`sudo service neo4j start`), then start running the script with:\n\n```\nphp main.php\n```\n\nThis will start importing in to Neo4j, printing out the results as it goes.\n\n[![](docs/images/stdout-resized.gif)](docs/images/stdout.gif)\n\nHere's an [annotated explanation of the results](docs/images/stdout-explained.png)\n\n### Tip:\n\n**You can stop and restart the script at any time, as the script stores its position using Redis.**\n\nThe script sets the following keys in Redis:\n\n* `bitcoin-to-neo4j` - This stores the number of the current blk.dat file, and it's position in that file.\n* `bitcoin-to-neo4j:orphans` - This stores the blockhashes of orphan blocks. You see, the blocks in the blk.dat files are not stored in order (based on their height), so by saving blocks that we cannot calculate a height for yet (because we haven't encountered the block it builds upon), we are able set the height later on.\n* `bitcoin-to-neo4j:tip` - This is the height of the current longest chain we have got in Neo4j. It's not needed for the script to work, but it's useful for seeing the progress of the script.\n* `bitcoin-to-neo4j:log` - Logs showing the amount of time that the blkXXXXX.dat files took to be imported.\n\nWhen Redis is installed, you can look at each of these with:\n\n```bash\nredis-cli hgetall bitcoin-to-neo4j\nredis-cli hgetall bitcoin-to-neo4j:orphans\nredis-cli hgetall bitcoin-to-neo4j:tip\nredis-cli hgetall bitcoin-to-neo4j:log\n```\n\n## FAQ\n\n### How does this work?\n\nI've written a complete guide on [how to import Bitcoin in to Neo4j](docs/how.md).\n\nIt covers the basic data structures of Bitcoin, and how to represent them in Neo4j.\n\n### How can I query this database?\n\nHere are some [example cypher queries](docs/cypher.md), including some screenshots.\n\n### What are the hardware requirements?\n\n1. A really ****ing big SSD.\n\nOther than that, I run this on my _Thinkpad X220_ (8GB Ram, 4x2.60GHz CPU) without any problems. It took about 2 weeks to import the full _testnet_ blockchain (50GB total), but my laptop didn't explode.\n\nHowever, if you want to help things along:\n\n* Make sure you're using an **SSD** for fast write speeds.\n* Give as much **RAM** to Neo4j as possible. This helps with looking up existing nodes in the database, which this script does continually as it merges new transactions on to old ones.\n    * Heap Size: I think a minimum 4GB does the trick.\n    * Page Cache: Whatever RAM you have got left over.\n\nCPU isn't much of a factor in comparison to RAM and a fast disk.\n\n_See [Neo4j Performance](http://neo4j.com/docs/operations-manual/current/performance/) for more details._\n\n### How big is this graph database?\n\nIt's constantly growing, but as of 17 May 2017 (blockchain height: 466,874, blockchain size: 114GB):\n\n* Nodes: 1,587,199,550 \n* Relationships: 2,503,359,310\n* Size: 625 GB\n\n### Does this import the _entire_ blockchain?\n\nYes, no data is left behind. If you really wanted to you could convert the data back in to binary as it is found in the raw `blk.dat` files.\n\nFor example, the \"serialized\" transaction data<sup>[2](#transaction-data)</sup>  on my explorer is actually data from the graph converted back in to it's original format: [Transaction: be56667fed4336efc08c6a1addfba0008169861af906e7f436ffcc86935d2b2e](http://learnmeabitcoin.com/browser/transaction/be56667fed4336efc08c6a1addfba0008169861af906e7f436ffcc86935d2b2e) _(click on \"serialized\" in the top-right)_\n\n### Why doesn't this use Neo4j's _Bulk Import Tool_?\n\nBecause I needed a script that would add blocks as they arrived.\n\nIt would involve writing another tool for a bulk import. I haven't tried.\n\n### Why is this written in PHP?\n\nBecause it's the language I knew best when I started this.\n\nOr in other words, I'm not the king of programming, and PHP does the job.\n\n## Footnotes\n\n* <a name=\"blkdat\">1</a>: <http://learnmeabitcoin.com/glossary/blkdat>\n* <a name=\"transaction-data\">2</a>: <http://learnmeabitcoin.com/glossary/transaction-data>\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"require\": {\n        \"laudis/neo4j-php-client\": \"^2.0\",\n        \"ext-redis\": \"*\",\n        \"ext-gmp\": \"*\",\n        \"ext-bcmath\": \"*\",\n        \"ext-ctype\": \"*\"\n    },\n    \"config\": {\n        \"allow-plugins\": {\n          \"php-http/discovery\": true\n        }\n    }\n}\n"
  },
  {
    "path": "config.php",
    "content": "<?php\n\ndefine(\"BLOCKS\", '/home/user/.bitcoin/blocks');\ndefine(\"TESTNET\", false); // Probably not, but; are you reading blk.dat files from Bitcoin's testnet?\n\ndefine(\"NEO4J_USER\", 'neo4j');\ndefine(\"NEO4J_PASS\", 'neo4j');\ndefine(\"NEO4J_IP\", 'localhost');    \ndefine(\"NEO4J_PORT\", '7687');       // this is the port used for the bolt protocol\n\ndefine(\"REDIS_IP\", 'localhost');    \ndefine(\"REDIS_PORT\", '6379');\n"
  },
  {
    "path": "cypher/block-genesis.cypher",
    "content": "// Create Block\nMERGE (block:block {hash:$blockhash})\nMERGE (block)-[:coinbase]->(:output:coinbase)\nSET\n    block.size=$blocksize,\n    block.txcount=$txcount,\n    block.version=$version,\n    block.prevblock=$prevblock,\n    block.merkleroot=$merkleroot,\n    block.time=$timestamp,\n    block.bits=$bits,\n    block.nonce=$nonce\n\n// Set Height\nSET block.height=0\n\n// Return\nRETURN block.height as height, block.prevblock as prevblock"
  },
  {
    "path": "cypher/block.cypher",
    "content": "// Create Block\nMERGE (block:block {hash:$blockhash})\nMERGE (block)-[:coinbase]->(:output:coinbase)\nSET\n    block.size=$blocksize,\n    block.txcount=$txcount,\n    block.version=$version,\n    block.prevblock=$prevblock,\n    block.merkleroot=$merkleroot,\n    block.time=$timestamp,\n    block.bits=$bits,\n    block.nonce=$nonce\n\n// Create Chain\nMERGE (prevblock:block {hash:$prevblock})\nMERGE (block)-[:chain]->(prevblock)\n\n// Set Height\nSET block.height=prevblock.height+1\n\n// Return\nRETURN block.height as height, block.prevblock as prevblock"
  },
  {
    "path": "cypher/tx-coinbase.cypher",
    "content": "// Create Transaction\nMATCH (block :block {hash:$blockhash})-[:coinbase]->(coinbase :coinbase)\nMERGE (tx:tx {txid:$txid})\nMERGE (tx)-[:inc {i:$t}]->(block)\nSET tx += $tx\n\n// Coinbase Input\nMERGE (coinbase)-[coinbasein:in {vin:0, scriptSig:$coinbase_script, sequence:$coinbase_sequence}]->(tx)\nFOREACH (input in $inputs |\n  SET coinbasein.witness = input.witness\n)\n\n// Outputs\nWITH tx\nFOREACH (output in $outputs |\n  MERGE (out :output {index: output.index})\n  MERGE (tx)-[:out {vout: output.vout}]->(out)\n  // This uses the foreach hack to only create an address node if the address value is not an empty string\n  FOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |\n    MERGE (address :address {address: output.addresses})\n\t\tMERGE (out)-[:locked]->(address)\n\t)\n\n  MERGE (out)-[:in]->(existing)\n  ON CREATE SET\n    out.value= output.value,\n    out.scriptPubKey= output.scriptPubKey\n  ON MATCH SET\n    out.value= output.value,\n    out.scriptPubKey= output.scriptPubKey,\n    existing.fee = existing.fee + output.value\n)\n\n// Fee\nWITH tx\nMATCH (i :output)-[:in]->(tx)\nWITH tx, sum(i.value) - $outtotal as fee\nSET tx.fee=fee\n\n// Return\nRETURN fee"
  },
  {
    "path": "cypher/tx.cypher",
    "content": "// Create Transaction\nMATCH (block :block {hash:$blockhash})\nMERGE (tx:tx {txid:$txid})\nMERGE (tx)-[:inc {i:$t}]->(block)\nSET tx += $tx\n\n// Inputs\nWITH tx\nFOREACH (input in $inputs |\n\tMERGE (in :output {index: input.index})\n\tMERGE (in)-[:in {vin: input.vin, scriptSig: input.scriptSig, sequence: input.sequence, witness: input.witness}]->(tx)\n\tREMOVE in:unspent\n)\n\n// Outputs\nFOREACH (output in $outputs |\n\tMERGE (out :output {index: output.index})\n\tMERGE (tx)-[:out {vout: output.vout}]->(out)\n  // This uses the foreach hack to only create an address node if the address value is not an empty string\n\tFOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |\n\t\tMERGE (address :address {address: output.addresses})\n\t\tMERGE (out)-[:locked]->(address)\n\t)\n\n\tMERGE (out)-[:in]->(existing)\n\tON CREATE SET\n\t\tout.value= output.value,\n\t\tout.scriptPubKey= output.scriptPubKey\n\tON MATCH SET\n\t\tout.value= output.value,\n\t\tout.scriptPubKey= output.scriptPubKey,\n\t\texisting.fee = existing.fee + output.value\n)\n\n// Fee\nWITH tx\nMATCH (i :output)-[:in]->(tx)\nWITH tx, sum(i.value) - $outtotal as fee\nSET tx.fee=fee\n\n// Return\nRETURN fee"
  },
  {
    "path": "cyphertx.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction cypherTx($neo, $transaction, $t, $blockhash, $cypher) {\n\n\t// =================\n\t// Cypher Parameters\n\t// =================\n\t$decoded = decoderawtransaction($transaction); // decode the raw transaction string\n\n\t$size = strlen($transaction)/2; $sizedisplay = str_pad('['. $size .' bytes]', 15, ' ');\n\t$relationshipsdisplay = str_pad('('. count($decoded['vin']) .':'. count($decoded['vout']) .')', 7, ' ');\n\t$txid = $decoded['txid'];\n\t$t_display = str_pad($t.'.', 5, ' ');\n\n\techo \"   $t_display $txid $sizedisplay $relationshipsdisplay \";\n\n\t// skip transaction if it already exists in database\n\t$check = $neo->run('MATCH (tx :tx {txid:$txid}) RETURN tx', ['txid' => $txid]);\n\t$exists = !$check->isEmpty(); // is there a record for this txid?\n\n\tif ($exists) {\n\n\t\t// if this is a coinbase transaction, always merge it to the block (because two coinbase txs can have the same txid)\n\t\tif ($decoded['vin'][0]['txid'] == '0000000000000000000000000000000000000000000000000000000000000000') {\n\t\t\t$vin_coinbase = $decoded['vin'][0]['scriptSig']['hex']; // miners can put what they like in it\n\t\t\t$vin_sequence = $decoded['vin'][0]['sequence'];\n\n\t\t\t$neo->run('\n\t\t\tMATCH (tx :tx {txid:$txid}), (block :block {hash:$blockhash})-[:coinbase]->(coinbase :output:coinbase)\n\t\t\tWITH tx, block, coinbase\n\t\t\tMERGE (tx)-[:inc {i:$t}]->(block)\n\t\t\tMERGE (coinbase)-[in :in]->(tx)\n\t\t\tON CREATE SET\n\t\t\t\tin.vin=0,\n\t\t\t\tin.scriptSig=$vin_coinbase,\n\t\t\t\tin.sequence=$vin_sequence\n\t\t\t',\n\t\t\t[\n\t\t\t\t'txid'         => $txid,\n\t\t\t\t'blockhash'    => $blockhash,\n\t\t\t\t't'            => $t,\n\t\t\t\t'vin_coinbase' => $vin_coinbase,\n\t\t\t\t'vin_sequence' => $vin_sequence,\n\t\t\t]\n\t\t\t);\n\n\t\t\techo 'exists->block (+coinbase)';\n\t\t}\n\n\t\telse {\n\t\t\t// just connect this transaction to the block (in case we've got a transaction from an orphan block - don't want to forget to connect it to the block)\n\t\t\t$neo->run('\n\t\t\tMATCH (tx :tx {txid:$txid}), (block :block {hash:$blockhash})\n\t\t\tWITH tx, block\n\t\t\tMERGE (tx)-[:inc {i:$t}]->(block)\n\t\t\t',\n\t\t\t[\n\t\t\t\t'txid'         => $txid,\n\t\t\t\t'blockhash'    => $blockhash,\n\t\t\t\t't'            => $t,\n\t\t\t]\n\t\t\t);\n\n\t\t\techo 'exists->block';\n\t\t}\n\n\t}\n\t// if this transaction doesn't exist in neo4j...\n\telse {\n\n\t\t// Build Parameter Array\n\t\t$parameters = array();\n\t\t$parameters['txid']      = $txid;\n\t\t$parameters['blockhash'] = $blockhash;\n\t\t$parameters['t']         = $t;\n\n\t\t// ----------\n\t\t// 1. TX node\n\t\t// ----------\n\t\t$parameters['tx']['version']  = $decoded['version'];\n\t\t$parameters['tx']['locktime'] = $decoded['locktime'];\n\t\t$parameters['tx']['size']     = $decoded['size'];\n\t\tif ($decoded['segwit']) {\n\t\t\t$parameters['tx']['segwit'] = $decoded['segwit']; // [marker][flag]\n\t\t}\n\n\t\t// ---------\n\t\t// 2. Inputs\n\t\t// ---------\n\t\t$i=0;\n\t\t$inputs = array();\n\t\t$coinbase = false; // will use this later to choose correct cypher query (coinbase transaction is slightly different to standard transaction)\n\n\t\tforeach ($decoded['vin'] as $vin) {\n\n\t\t\t// Store new witness data if this is a new Segregated Witness transaction\n\t\t\tif (array_key_exists('witness', $vin)) {\n\t\t\t\t$witness = $vin['witness']['hex'];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$witness = '';\n\t\t\t}\n\n\t\t\t$vin_txid                = $vin['txid']; // (no need to swapEndian - txid is already in searchable order)\n\t\t\t$vin_vout                = $vin['vout'];\n\t\t\t$vin_scriptSig           = $vin['scriptSig']['hex'];\n\t\t\t$vin_sequence            = $vin['sequence'];\n\t\t\t\t\n\t\t\t$inputs[$i]['vin']       = $i;\n\t\t\t$inputs[$i]['index']     = \"$vin_txid:$vin_vout\";\n\t\t\t$inputs[$i]['scriptSig'] = $vin_scriptSig;\n\t\t\t$inputs[$i]['sequence']  = $vin_sequence;\n\t\t\t$inputs[$i]['witness']   = $witness;\n\n\t\t\t$i++;\n\t\t}\n\n\t\t// If coinbase transaction\n\t\tif ($decoded['vin'][0]['txid'] == '0000000000000000000000000000000000000000000000000000000000000000') { // the input txid is all zeros for coinbase transactions\n\t\t\t$coinbase = true;\n\t\t\t$parameters['coinbase_script'] = $inputs[0]['scriptSig']; // miners can put what they like in this\n\t\t\t$parameters['coinbase_sequence'] = $inputs[0]['sequence'];\n\t\t}\n\n\t\t$parameters['inputs'] = $inputs;\n\n\t\t// ----------\n\t\t// 3. Outputs\n\t\t// ----------\n\t\t$i=0;\n\t\t$outputs = [];\n\t\t$outtotal = 0; // keep track of output values (for calculating fee later)\n\n\t\tforeach ($decoded['vout'] as $vout) {\n\n\t\t\t$value = $vout['value'];\n\t\t\t$scriptPubKey = $vout['scriptPubKey']['hex'];\n\t\t\t$addresses = $vout['scriptPubKey']['addresses'];\n\n\t\t\t$outputs[$i]['vout'] = $i;\n\t\t\t$outputs[$i]['index'] = \"$txid:$i\";\n\t\t\t$outputs[$i]['value'] = $value;\n\t\t\t$outputs[$i]['scriptPubKey'] = $scriptPubKey;\n\t\t\t$outputs[$i]['addresses'] = $addresses;\n\t\t\t\n\t\t\t$outtotal += $value;\n\t\t\t$i++;\n\n\t\t}\n\n\t\t$parameters['outputs'] = $outputs;\n\t\t$parameters['outtotal'] = $outtotal;\n\n\n\t\t// ============\n\t\t// Cypher Query\n\t\t// ============\n\n\t\t// Select Cypher Query\n\t\tif ($coinbase) {\n\t\t\t$query = $cypher['tx-coinbase'];\n\t\t}\n\t\telse {\n\t\t\t$query = $cypher['tx'];\n\t\t}\n\n\t\t// Run the full query to add the tx to the neo4j db (returns input total)\n\t\twhile (true) {\n\t\t\t// Catch any errors caught by locks on nodes when writing to Neo4j\n\t\t\ttry {\n\t\t\t\t$result = $neo->run($query, $parameters);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// Echo the error, then wait a second before trying again.\n\t\t\tcatch (Exception $e) {\n\t\t\t\techo $e;\n\t\t\t\texit;\n\t\t\t\tsleep(1);\n\t\t\t}\n\t\t}\n\n\t\t// Get the fee (just to check) (Note: The fee will be negative if the inputs for this transaction are not in Neo4j yet, which is cool.)\n\t\t$fee = $result->first()->get('fee');\n\t\techo \"fee: $fee\";\n\n\t\treturn $fee;\n\n\t}\n\n}\n"
  },
  {
    "path": "docs/benchmark.md",
    "content": "# Benchmarks\n\nI did a few rough tests for common/useful bitcoin queries, each returning various numbers of nodes. I repeated each query 3 times.\n\nTimes are in ms (milliseconds).\n\n## Blocks\n\nGetting a block and all the transactions connected to it.\n\n|Rows    |Time  |Time|Time|\n|--------|------|----|----|\n|2764    |1335  |282 |49  |\n|1745    |1261  |37  |35  |\n|687     |212   |19  |18  |\n|550     |187   |18  |15  |\n\n### Query\n\n```\nPROFILE MATCH (b:block)<-[:inc]-(t:tx) WHERE b.hash='000000000000000000ebaa7b3a804d9ba856b3bd61659f8f363bd42dc9c4a94c' RETURN b, t\n```\n\n## Transactions\n\nGetting a transaction and all the inputs/outputs connected to it.\n\n|Rows    |Time|Time|Time|\n|--------|----|----|----|\n|5026    |897 |282 |269 |\n|94      |85  |17  |17  |\n|4       |33  |8   |6   |\n\n### Query\n\n```\nPROFILE MATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs) WHERE tx.txid='c21e2592abcd3eea532f51f3e18bbc9d9ad23b44f643d9aea580bf0ce0d4d0bc' OPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses) OPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses) OPTIONAL MATCH (tx)-[:inc]->(block) RETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses\n```\n\n## Addresses\n\nGetting an address and all the outputs connected to it.\n\n|Rows    |Time  |Time|Time|\n|--------|------|----|----|\n|3195800 |-     |-   |-   |\n|27071   |12904 |344 |357 |\n|830     |560   |13  |15  |\n|188     |191   |15  |7   |\n\nNote: The top query took over 60s to run each time, so I didn't get a final time for it.\n\n### Query\n\n```\nMATCH (address :address)<-[:locked]-(output :output) WHERE address.address='$address' RETURN address, output\n```\n\n## Conclusion\n\nNeo4j is fast enough for practical use.\n\nThe only query that really struggles is the addresses that have 300,000+ outputs attached to them. But these are rare. However for those the time becomes impractical."
  },
  {
    "path": "docs/cypher.md",
    "content": "# Cypher Queries\n\nHere are some example Cypher queries for getting useful data out of the Bitcoin Neo4j database.\n\n## Blockchain\n\n![](images/blockchain.png)\n\n```\nMATCH (start :block {height:100})-[chain :chain*0..4]->(block :block)-[:coinbase]->(cb :output)-[:in]->(coinbasetx :tx)\nRETURN block, cb\n```\n\nReturn a chain of blocks from a particular starting height, along with the coinbase (containing the block reward) from each block.\n\n## Transaction.\n\n![](images/transaction.png)\n\n```\nMATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs)\nWHERE tx.txid='$txid'\nOPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses)\nOPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses)\nOPTIONAL MATCH (tx)-[:inc]->(block)\nRETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses\n```\n\nThis will give you a transaction node with all of its inputs and all of its outputs, and any addresses those outputs are locked to. It will also return the block(s) the transaction is included in.\n\n_Note: A transaction can be included in more than one block; in a block on the main chain, and in a block on a fork of the main chain. This typically happens when two different blocks are mined at the same time._\n\n## Block\n\n![](images/block.png)\n\n```\nMATCH (block :block)<-[:inc]-(tx :tx)\nWHERE block.hash='$blockhash'\nRETURN block, tx\n```\n\nThis returns a block with all the transactions that are included in it.\n\n## Address\n\n![](images/address.png)\n\n```\nMATCH (address :address)<-[:locked]-(output :output)\nWHERE address.address='$address'\nRETURN address, output\n```\n\nShow all of the outputs that have been locked to an address.\n\n_Note: Addresses are found from the scriptSig field of an output._\n\n### Address Balance\n\n```\nMATCH (address :address)<-[:locked]-(output :output) \nWHERE address.address='$address' \nAND NOT (output)-[:in]->(:tx) \nRETURN sum(output.value) as balance\n```\n\nYou can calculate the balance of an address by summing the values of the _unspent_ outputs that are locked to an address.\n\n_Note: An unspent output is one that has not been included as an input in another transaction (`AND NOT (output)-[:in]->(:tx)`)._\n\n## Paths\n\n### Between Outputs\n\n![](images/path_output.png)\n\n```\nMATCH (start :output {index:'$txid:vout'})\nWITH start\nMATCH (end :output {index:'$txid:vout'})\nMATCH path=shortestPath( (start)-[:in|out*1..100]-(end) )\nRETURN path\n```\n\nAn output is like a single payment of bitcoins. This query allows you to see if two payments (outputs) are connected by a series of transactions.\n\n_Note: Each output has a unique index property, which is a combination of the ID of the transaction it was created in (txid) and, and the output number from that transaction (vout). So an index would look something like this: `302c4757c5eb9f1633d5d076f150d320b8418f3a6295f5e87fc1805b9440cbc0:1`._\n\n### Between Addresses\n\n![](images/path_address.png)\n\n```\nMATCH (start :address {address:'$address1'})\nWITH start\nMATCH (end :address {address:'$address2'})\nMATCH path=shortestPath( (start)-[:in|out|locked*1..100]-(end) )\nRETURN path\n```\n\nThis query allows you to see if two address are connected by a series of transactions. It also returns a path if there are common intermediary addresses.\n\n### Between Addresses (Multiple Paths)\n\n```\nMATCH (start :address {address:'$address1'})\nWITH start\nMATCH (end :address {address:'$address2'})\nMATCH path=allShortestPaths( (start)-[:in|out|locked*1..100]-(end) )\nRETURN path\nLIMIT 5\n```\n\nThis is the most interesting query if you're looking to visualize all the connections between two addresses. It's best to start with a low `LIMIT` (i.e. small number of paths) and go from there.\n\n## Historical Analyses\n\n### First Transctions\n\nThe following query finds all non-coinbase transactions in the first 1000 blocks.\n\n```cypher\nMATCH (block:block)-[:inc]-(tx:tx)\nWHERE block.height < 1000\n  AND not exists((tx)<-[:in]-(:coinbase))\nRETURN\n  block.height AS block,\n  tx.txid AS transaction,\n  size((tx)<-[:in]-()) AS inputs,\n  size((tx)-[:out]->()) AS outputs,\n  tx.fee / tx.size AS fee_satoshis_per_byte\nORDER BY block\n```\n\nThe first few rows returned are:\n\n| block | transaction | inputs | outputs | fee_satoshis_per_byte |\n|-------|-------------|--------|---------|-----------------------|\n| 170 | f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16 | 1 | 2 | 0 |\n| 181 | a16f3ce4dd5deb92d98ef5cf8afeaf0775ebca408f708b2146c4fb42b41e14be | 1 | 2 | 0 |\n| 182 | 591e91f809d716912ca1d4a9295e70c3e78bab077683f79350f101da64588073 | 1 | 2 | 0 |\n"
  },
  {
    "path": "docs/how.md",
    "content": "# How to Import the Blockchain in to Neo4j\n\n![Screenshot of the blockchain in the Neo4j browser.](images/how/neo4j-bitcoin.png)\n\nThis guide runs through the _basic_ steps for **importing the bitcoin blockchain in to a Neo4j graph database**.\n\nThe whole process is just about taking data from one format (blockchain data), and converting it in to another format (a graph database). The only thing that makes this slightly trickier than typical data conversion is that it's _helpful_ to understand of the structure of bitcoin data before you get started.\n\nHowever, once you have imported the blockchain in to Neo4j, you can perform analysis on the graph database that would not be possible with SQL databases. For example, you can **follow the path of bitcoins to see if two different addresses are connected**:\n\n![Screenshot of connected Bitcoin addresses in the Neo4j browser.](images/how/neo4j-connected-addresses.png)\n\nIn this guide I will cover:\n\n1. How bitcoin works, and what the blockchain is.\n2. What blockchain data looks like.\n3. How to import the blockchain data in to Neo4j.\n\nThis isn't a complete tutorial on how to write your own importer tool. However, if you're interested, you look at my [bitcoin-to-neo4j](https://github.com/in3rsha/bitcoin-to-neo4j) code, although I'm sure you could write something cleaner after reading this guide.\n\n\n## 1. What is Bitcoin?\n\nBitcoin is a computer program.\n\nIt's a bit like uTorrent; you run the program, it _connects to other computers_ running the same program, and it _shares a file_. However, the cool thing about Bitcoin is that _anyone can add data_ to this shared file, and any data already written to the file _cannot be tampered with_.\n\n![](images/how/bitcoin-network.gif)\n\nAs a result, Bitcoin creates a **secure file** that is shared on a **distributed network**.\n\n### What can you do with this?\n\nWell, in Bitcoin, each piece of data that gets added to this file is a **transaction**. Therefore, this decentralised file is being used as a \"ledger\" for a _digital currency_.\n\nThis ledger is called **the blockchain**.\n\n![](images/how/bitcoin-file.gif)\n\n### Where can I find the blockchain?\n\nIf you run the [Bitcoin Core](https://bitcoin.org/en/download) program, the blockchain will be stored in a folder on your computer:\n\n* Linux: `~/.bitcoin/blocks`\n* Windows: `~/Library/Application Support/Bitcoin/blocks`\n* Mac: `C:\\Users\\YourUserName\\Appdata\\Roaming\\Bitcoin\\blocks`\n\n**NOTE:** When you open this directory you should notice that instead of one big file, you will find multiple files with the name `blkXXXXX.dat`. This is the blockchain data, but split across multiple smaller files.\n\n\n\n\n## 2. What does the blockchain look like?\n\nThe [blk.dat](https://learnmeabitcoin.com/technical/blkdat) files contain serialized data of **blocks** and **transactions**.\n\n![](images/how/blockchain.png)\n\n### Blocks\n\nBlocks are separated by [magic bytes](https://learnmeabitcoin.com/technical/magic-bytes), which is then followed by the _size_ of the upcoming block.\n\nEach block then begins with a [block header](https://learnmeabitcoin.com/technical/block-header):\n\n![A block is basically a container for a list of transactions. The header is like the meta-data at the top.](images/how/blockchain-block.png)\n\n#### Block Header Example:\n\n```\n{\n  \"version\": 00000020,\n  \"previousblock\": \"6c77f112319ae21489b66774e8acd379044d4a23ea7498000000000000000000\",\n  \"merkleroot\": \"821fe1890186779b2cc232d5dbecfb9119fd46f8a9cfd1141649ff1cd9073744\",\n  \"time\": 87d8ae59,\n  \"bits\": \"e93c0118\",\n  \"nonce\": 32ec0399,\n}\n```\n\n### Transactions\n\nAfter the block header, there is a byte that tells you the upcoming number of transactions in the block. After that, you get serialized transaction data, one after the other.\n\nA [transaction](https://learnmeabitcoin.com/technical/transaction-data) is just another piece of code again, but they are more structurally interesting.\n\n![](images/how/blockchain-transaction.png)\n\nEach transaction has the same pattern:\n\n1. Select Outputs (we call these _Inputs_).\n    * _Unlock_ these inputs so that they can be spent.\n2. Create Outputs\n    * _Lock_ these outputs to a new address.\n\nSo after a series of transactions, you have a transaction structure that looks like something this:\n\n![This is a simplified diagram of what the blockchain looks like. As you can see, it looks like a graph.](images/how/blockchain-transactions.png)\n\n\n#### Transaction Example:\n\n```\n{\n  \"version\": \"02000000\",\n  \"inputcount\": \"01\",\n  \"inputs\": [\n    {\n      \"txid\": \"f2f7ee9dda0ba82031858d30d50d3205eea07246c874a0488532014d3b653f03\",\n      \"vout\": \"00000000\",\n      \"scriptsigsize\": \"6a\",\n      \"scriptsig\": \"47304402204df1839028a05b5b303f5c85a66affb7f6010897d317ac9e88dba113bb5a0fe9022053830b50204af15c85c9af2b446338d049672ecfdeb32d5124e0c3c2256248b7012102c06aec784f797fb400001c60aede8e110b1bbd9f8503f0626ef3a7e0ffbec93b\",\n      \"sequence\": \"feffffff\"\n    }\n  ],\n  \"outputcount\": \"02\",\n  \"outputs\": [\n    {\n      \"amount\": \"00e1f50500000000\",\n      \"scriptpubkeysize\": \"19\",\n      \"scriptpubkey\": \"76a9144120275dbeaeb40920fc71cd8e849c563de1610988ac\"\n    },\n    {\n      \"amount\": \"9f16641800000000\",\n      \"scriptpubkeysize\": \"19\",\n      \"scriptpubkey\": \"76a91493fa3301df8b0a268c7d2c3cc4668ea86fddf81588ac\"\n    }\n  ],\n  \"locktime\": \"61610700\"\n}\n```\n\n\n\n\n\n## 3. How to import the blockchain in to Neo4j.\n\nWell, now we know what the blockchain data represents (and that it looks a lot like a graph), we can go ahead and import it in to Neo4j. We do this by:\n\n1. Reading through the blk.dat files.\n2. Decoding each block and transaction we run in to.\n3. Converting the decoded block/transaction in to a Cypher query.\n\nHere's a visual guide to how I represent **Blocks**, **Transactions**, and **Addresses** in the database:\n\n### Blocks\n\n![](images/how/import-block.gif)\n\n1. CREATE a `:block` node, and connect it to the previous block it builds upon.\n    * SET each field from the **block header** as _properties_ on this node.\n3. CREATE a `:coinbase` node coming off each block, as this represents the \"new\" bitcoins being made available by the block.\n    * SET a **value** property on this node, which is equal to the block reward for this block.\n\n### Transactions\n\n![](images/how/import-transaction.gif)\n\n1. CREATE a `:tx` node, and connect it to the `:block` we had just created.\n    * SET properties (**version**, **locktime**) on this node.\n2. MERGE existing `:output` nodes and relate them `[:in]` to the `:tx`.\n    * SET the **unlocking** code as a property on the relationship.\n3. CREATE new `:output` nodes that this transaction creates.\n    * SET the respective **values** and **locking** codes on these nodes.\n\n#### Addresses\n\nIf the **locking** code on an `:output` contains an address...\n\n![](images/how/import-address.gif)\n\n1. CREATE an `:address` node, and connect the output node to it.\n    * SET the **address** as a property on this node.\n    * _Note: If different outputs are connected to the same address, then they will be connected to the same address node._\n\n\n\n\n\n## 4. Cypher Queries\n\nHere are some example cypher queries you could use for the basis of inserting blocks and transactions in to Neo4j.\n\n**NOTE:** You will need to decode the **block headers** and **transaction data** to get the _parameters_ for the cypher queries.\n\n### Block\n\n```cypher\nMERGE (block:block {hash:$blockhash})\nCREATE UNIQUE (block)-[:coinbase]->(:output:coinbase)\nSET\n   block.size=$size,\n   block.prevblock=$prevblock,\n   block.merkleroot=$merkleroot,\n   block.time=$timestamp,\n   block.bits=$bits,\n   block.nonce=$nonce,\n   block.txcount=$txcount,\n   block.version=$version,\n\nMERGE (prevblock:block {hash:$prevblock})\nMERGE (block)-[:chain]->(prevblock)\n```\n\n#### Parameters (example):\n```json\n{\n    \"blockhash\": \"00000000000003e690288380c9b27443b86e5a5ff0f8ed2473efbfdacb3014f3\",\n    \"version\": 536870912,\n    \"prevblock\": \"000000000000050bc5c1283dceaff83c44d3853c44e004198c59ce153947cbf4\",\n    \"merkleroot\": \"64027d8945666017abaf9c1b7dc61c46df63926584bed7efd6ed11a6889b0bac\",\n    \"timestamp\": 1500514748,\n    \"bits\": \"1a0707c7\",\n    \"nonce\": 2919911776,\n    \"size\": 748959,\n    \"txcount\": 1926,\n}\n```\n\n### Transaction\n\n```cypher\nMATCH (block :block {hash:$hash})\nMERGE (tx:tx {txid:$txid})\nMERGE (tx)-[:inc {i:$i}]->(block)\nSET tx += {tx}\t  \n\nWITH tx\nFOREACH (input in $inputs |\n\t\t MERGE (in :output {index: input.index})\n\t\t MERGE (in)-[:in {vin: input.vin, scriptSig: input.scriptSig, sequence: input.sequence, witness: input.witness}]->(tx)\n\t\t )\n\nFOREACH (output in $outputs |\n\t\t MERGE (out :output {index: output.index})\n\t\t MERGE (tx)-[:out {vout: output.vout}]->(out)\n\t\t SET\n\t\t     out.value= output.value,\n\t\t     out.scriptPubKey= output.scriptPubKey,\n\t\t     out.addresses= output.addresses\n\t\t FOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |\n\t\t\t\t MERGE (address :address {address: output.addresses})\n\t\t\t\t MERGE (out)-[:locked]->(address)\n\t\t\t\t )\n\t\t )\n```\n\n_Note: This query uses the [FOREACH hack](http://www.markhneedham.com/blog/2016/10/30/neo4j-create-dynamic-relationship-type/), which acts as a conditional and will only create the `:address` nodes if the `$addresses` parameter actually contains an address (i.e. is not empty)._\n\n#### Parameters (example):\n\n```json\n{\n    \"txid\": \"2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c\",\n    \"hash\": \"00000000000003e690288380c9b27443b86e5a5ff0f8ed2473efbfdacb3014f3\",\n    \"i\": 1,\n    \"tx\": {\n        \"version\": 1,\n        \"locktime\": 0,\n        \"size\": 237,\n        \"weight\": 840,\n        \"segwit\": \"0001\"\n    },\n    \"inputs\": [\n        {\n            \"vin\": 0,\n            \"index\": \"0000000000000000000000000000000000000000000000000000000000000000:4294967295\",\n            \"scriptSig\": \"03779c110004bc097059043fa863360c59306259db5b0100000000000a636b706f6f6c212f6d696e65642062792077656564636f646572206d6f6c69206b656b636f696e2f\",\n            \"sequence\": 4294967295,\n            \"witness\": \"01200000000000000000000000000000000000000000000000000000000000000000\"\n        }\n    ],\n    \"outputs\": [\n        {\n            \"vout\": 0,\n            \"index\": \"2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c:0\",\n            \"value\": 166396426,\n            \"scriptPubKey\": \"76a91427f60a3b92e8a92149b18210457cc6bdc14057be88ac\",\n            \"addresses\": \"14eJ6e2GC4MnQjgutGbJeyGQF195P8GHXY\"\n        },\n        {\n            \"vout\": 1,\n            \"index\": \"2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c:1\",\n            \"value\": 0,\n            \"scriptPubKey\": \"6a24aa21a9ed98c67ed590e849bccba142a0f1bf5832bc5c094e197827b02211291e135a0c0e\",\n            \"addresses\": \"\"\n        }\n    ]\n}\n```\n\n\n## 5. Results\n\nIf you have inserted the blocks and transactions using the cypher queries above, then these are some examples the kind of results you can get out of the graph database.\n\n### Block\n\n![](images/how/results-block.png)\n\n```\nMATCH (block :block)<-[:inc]-(tx :tx)\nWHERE block.hash='$blockhash'\nRETURN block, tx\n```\n\n### Transaction\n\n![](images/how/results-transaction.png)\n\n```\nMATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs)\nWHERE tx.txid='$txid'\nOPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses)\nOPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses)\nOPTIONAL MATCH (tx)-[:inc]->(block)\nRETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses\n```\n\n### Address\n\n![](images/how/results-address.png)\n\n```\nMATCH (address :address {address:'1PNXRAA3dYTzVRLwWG1j3ip9JKtmzvBjdY'})<-[:locked]-(output :output)\nWHERE address.address='$address'\nRETURN address, output\n```\n\n### Paths\n\nFinding paths between transactions and addresses is probably the most interesting thing you can do with a graph database of the bitcoin blockchain, so here are some examples of cypher queries for that:\n\n#### Between Outputs\n\n![](images/how/results-path-output.png)\n\n```\nMATCH (start :output {index:'$txid:vout'}), (end :output {index:'$txid:out'})\nMATCH path=shortestPath( (start)-[:in|:out*]-(end) )\nRETURN path\n```\n\n#### Between Addresses\n\n![](images/how/results-path-address.png)\n\n\n```\nMATCH (start :address {address:'$address1'}), (end :address {address:'$address2'})\nMATCH path=shortestPath( (start)-[:in|:out|:locked*]-(end) )\nRETURN path\n```\n\n\n\n## 6. Conclusion\n\nThis has been a simple guide on how you can take the blocks and transactions from blk.dat files (the blockchain) and import them in to a Neo4j database.\n\nI think it's worth the effort if you're looking to do serious analysis on the blockchain. A graph database is a natural fit for bitcoin data, whereas using an SQL database for bitcoin transactions feels like trying to shove a square peg in to a round hole.\n\nI've tried to keep this guide compact, so I haven't covered things like:\n\n1. **Reading through the blockchain.** Reading the [blk.dat](https://learnmeabitcoin.com/technical/blkdat) files is easy enough. However, the annoying thing about these files is that the **blocks are [not written to these files in sequential order](https://bitcoin.stackexchange.com/questions/41535/how-much-out-of-order-are-the-blocks-stored-in-the-blk-dat-files)**, which makes _setting the height on a block_ or _calculating the fee for a transaction_ a bit trickier (but you can code around it).\n2. **Decoding blocks and transactions.** If you want to use the **cypher queries** above, you will need to get the _parameters_ you require by decoding the block headers and raw transaction data as you go. You could write your own decoders, or you could try using an existing bitcoin library.\n3. **Segregated Witness**. I've only given a cypher query for an \"original\" style transaction, which was the only transaction structure used up until block [481,824](https://learnmeabitcoin.com/explorer/blockchain/481824). However, the structure of a [segwit transaction](https://learnmeabitcoin.com/explorer/transaction/c586389e5e4b3acb9d6c8be1c19ae8ab2795397633176f5a6442a261bbdefc3a) is only slightly different (but it might need its own cypher query).\n\nNonetheless, hopefully this guide has been somewhat helpful.\n\nBut as always, if you understand how the data works, converting it to a different format is just a matter of sitting down and writing the tool.\n\nGood luck.\n"
  },
  {
    "path": "functions/README.md",
    "content": "# Library Functions\n\nThis is a bunch of simple library functions for Bitcoin. I use them for decoding the raw transaction data found in Bitcoin's `blk.dat` files (binary files containing the blockchain).\n\nI wrote this library for speed. For a more comprehensive library, check out [bitcoin-php](https://github.com/Bit-Wasp/bitcoin-php)\n"
  },
  {
    "path": "functions/basic.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction swapEndian($data) {\n    return implode('', array_reverse(str_split($data, 2)));\n}\n\nfunction fieldSize($field, $bytes = 4) {\n    $length = $bytes * 2;\n    $result = str_pad($field, $length, '0', STR_PAD_LEFT);\n    return $result;\n}\n\nfunction ascii2hex($ascii) {\n\t$hex = '';\n\tfor ($i = 0; $i < strlen($ascii); $i++) {\n\t\t$byte = strtoupper(dechex(ord($ascii[$i])));\n\t\t$byte = str_repeat('0', 2 - strlen($byte)).$byte;\n\t\t$hex .= $byte;\n\t}\n\treturn $hex;\n}\n\nfunction hex2ascii($hex) {\n    $str = '';\n    for($i=0; $i<strlen($hex); $i+=2) {\n\t\t$byte = substr($hex, $i, 2);\n\t\t$dec = hexdec($byte);\n\t\t$str .= chr($dec);\n\t}\n    return filter_var($str, FILTER_SANITIZE_SPECIAL_CHARS); // Prevent an XSS attack from a hex encoded ascii string\n}\n\nfunction varInt($data) { // Calculates the full variable integer and returns it\n    $varint = strtolower(substr($data, 0, 2));\n\n    if     ($varint == 'fd') { $value = substr($data, 2, 4);  $full = $varint.$value; $len = 6;}\n    elseif ($varint == 'fe') { $value = substr($data, 2, 8);  $full = $varint.$value; $len = 10;}\n    elseif ($varint == 'ff') { $value = substr($data, 2, 16); $full = $varint.$value; $len = 18;}\n    else                     { $value = $varint; $full = $varint; $len = 2; }\n\n    $value = hexdec(swapEndian($value)); // convert value to a usable decimal number\n\n    return array($full, $value, $len);\n}\n\nfunction toVarInt($i) {\n\tif ($i < 253) {\n\t\treturn fieldSize(dechex($i), 1);\n\t}\n\tif (253 <= $i && $i < 65535) {\n\t\treturn 'fd'.swapEndian(fieldSize(dechex($i), 2));\n\t}\n\tif (65535 <= $i && $i < 4294967295) {\n\t\treturn 'fe'.swapEndian(fieldSize(dechex($i), 4));\n\t}\n\tif (4294967295 <= $i) {\n\t\treturn 'ff'.swapEndian(fieldSize(dechex($i), 8));\n\t}\n}\n\nfunction bchexdec($hex) {\n    if(strlen($hex) == 1) {\n        return hexdec($hex);\n    } else {\n        $remain = substr($hex, 0, -1);\n        $last = substr($hex, -1);\n        return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));\n    }\n}\n\nfunction bcdechex($dec) {\n    $last = bcmod($dec, 16);\n    $remain = bcdiv(bcsub($dec, $last), 16);\n\n    if($remain == 0) {\n        return dechex($last);\n    } else {\n        return bcdechex($remain).dechex($last);\n    }\n}\n\n"
  },
  {
    "path": "functions/block.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nrequire_once('basic.php');\n\nconst TARGET_MAX = '00000000FFFF0000000000000000000000000000000000000000000000000000';\n\nfunction calculateBlockReward($blockcount) {\n    // set the block rewards array\n    $reward = 5000000000;\n    $i = 1;\n    while ($reward >= 1) {\n        $blockrewards[$i] = $reward;\n        $reward = floor($reward/2);\n        $i++;\n    }\n\n    // work out the block reward level\n    $block = 0;\n    $level = 0;\n    while ($blockcount >= $block) {\n        $block += 210000;\n        $level += 1;\n    }\n\t\n\t// return the value in satoshis\n\treturn $blockrewards[$level];\n}\n\nfunction bitstotarget($bits) {\n \n\t// remove the 0x prefix (if it's there)\n\tif (substr($bits, 0, 2) == '0x') {\n\t\t$bits = ltrim($bits, '0x');\n\t}\n \n\t// get the two parts\n\t$exponent = substr($bits, 0, 2);\n\t$coefficient = substr($bits, 2, 6);\n \n\t// calculate the size of the target in bytes\n\t$bytes = hexdec($exponent);\n \n\t// form the size of the target with the coefficient at the start\n\t$target = str_pad($coefficient, (($bytes) * 2), '0' );\n \n\t// return a 32-byte target (without the 0x at the start)\n\treturn str_pad($target, 32*2, '0', STR_PAD_LEFT);\n \n}\n\nfunction bitstodifficulty($bits) {\n\n\t$targetmax = bchexdec(TARGET_MAX);\n\t$target    = bchexdec(bitstotarget($bits));\n\t$difficulty = $targetmax/$target;\n\n\treturn $difficulty;\n}\n\n\nfunction difficultytotarget($difficulty) {\n\t$targetmax = bchexdec(TARGET_MAX); //26959535291011309493156476344723991336010898738574164086137773096960';\n\t$target = bcdiv($targetmax, $difficulty);\n\t\n\treturn str_pad(bcdechex($target), 64, '0', STR_PAD_LEFT);\n}\n\nfunction targettobits($target) {\n\t$bytes = str_split($target, 2);\n\n\t// 1. coefficient\n\t$i = 1;\n\t$coefficient = '';\n\tforeach ($bytes as $byte) {\n\t\tif ($byte != '00' && $i <= 3) {\n\t\t\t$coefficient .= $byte;\n\t\t\t$i++;\n\t\t}\n\t}\n\n\t// 2. exponent\n\t$position = strpos($target, $coefficient);\n\t$exponent = dechex((64 - $position) / 2);\n\n\t// 3. bits\n\t$bits = $exponent.$coefficient;\n\treturn $bits;\n}\n\nfunction merklerootbinary($txids) {\n \n\t// Stop recursion if there is only one hash value left, because that's the merkle root.\n\tif (count($txids) == 1) {\n\t\t$merkleroot = $txids[0];\n\t\treturn $merkleroot;\n\t}\n \n\telse {\n \n\t\t// Create the new array of hashes\t\t\n\t\twhile (count($txids) > 0) {\n \n\t\t\tif (count($txids) >= 2) {\n\t\t\t\t// Get first two\n\t\t\t\t$pair_first = $txids[0];\n\t\t\t\t$pair_second = $txids[1];\n \n\t\t\t\t// Hash them (double SHA256)\n\t\t\t\t$pair = $pair_first.$pair_second;\n\t\t\t\t$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);\n \n\t\t\t\t// Remove those two from the array\n\t\t\t\tunset($txids[0]);\n\t\t\t\tunset($txids[1]);\n \n\t\t\t\t// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.\n\t\t\t\t$txids = array_values($txids);\n\t\t\t}\n \n\t\t\tif (count($txids) == 1) {\n\t\t\t\t// Get the first one twice\n\t\t\t\t$pair_first = $txids[0];\n\t\t\t\t$pair_second = $txids[0];\n \n\t\t\t\t// Hash it with itself (double SHA256)\n\t\t\t\t$pair = $pair_first.$pair_second;\n\t\t\t\t$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);\n \n\t\t\t\t// Remove it from the array\n\t\t\t\tunset($txids[0]);\n \n\t\t\t\t// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.\n\t\t\t\t$txids = array_values($txids);\n\t\t\t}\n \n\t\t}\n \n\t\t// Recursion bit. Re-apply this function to the new array of hashes we've just created.\n\t\treturn merklerootbinary($pairhashes);\n \n\t}\n \n}\n \nfunction merkleroot($txids) {\n \n\t// Convert txids in to big endian (BE), because that's the format they need to be in to get the merkle root.\n\tforeach ($txids as $txid) {\n\t\t$txidsBE[] = swapEndian($txid);\n\t}\n \n\t// Now convert each of these txids in to binary, because the hash function wants the binary value, not the hex.\n\tforeach ($txidsBE as $txidBE) {\n\t\t$txidsBEbinary[] = hex2bin($txidBE);\n\t}\n \n\t// Work out the merkle root (in binary) using that lovely recursive function above.\n\t$merkleroot = merklerootbinary($txidsBEbinary);\n \n\t// Convert the merkle root in to hexadecimal and little-endian, because that's how it's stored in the block header.\n\t$merkleroot = swapEndian(bin2hex($merkleroot));\n \n\t// Return it :)\n\treturn $merkleroot;\n \n}\n"
  },
  {
    "path": "functions/hash.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction hash256($hex) {\n\t$binary = hex2bin($hex);\n\t$hash1 = hash(\"sha256\", $binary, true); // \"true\" returns binary value (or will return hex by default)\n\t$hash2 = hash(\"sha256\", $hash1);\n\treturn $hash2;\n}\n  \nfunction hash160($hex) {\n\t$binary = hex2bin($hex);\n\t$hash1 = hash(\"sha256\", $binary, true);\n\t$hash2 = hash(\"ripemd160\", $hash1);\n\treturn $hash2;\n}\n"
  },
  {
    "path": "functions/keys.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'hash.php'; // hash256 and hash160\n\n// Taken from bitcoin-lib-php\nfunction base58_encode($hex)\n  {\n  \t\t$base58chars = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\n      if (strlen($hex) == 0) {\n          return '';\n      }\n\n      // Convert the hex string to a base10 integer\n      $num = gmp_strval(gmp_init($hex, 16), 58);\n\n      // Check that number isn't just 0 - which would be all padding.\n      if ($num != '0') {\n          $num = strtr(\n              $num,\n              '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv',\n              $base58chars\n          );\n      } else {\n          $num = '';\n      }\n\n      // Pad the leading 1's\n      $pad = '';\n      $n = 0;\n      while (substr($hex, $n, 2) == '00') {\n          $pad .= '1';\n          $n += 2;\n      }\n\n      return $pad . $num;\n  }\n\nfunction base58_encode_checksum($hex)\n  {\n      $checksum = hash256($hex);\n      $checksum = substr($checksum, 0, 8);\n      $hash = $hex . $checksum;\n      return base58_encode($hash);\n  }\n\nfunction hash160_to_address($hash160, $prefix = '00')\n\t{\n\t  // 00 = 1address\n\t  // 05 = 3address\n      $hash160 = $prefix.$hash160;\n      return base58_encode_checksum($hash160);\n\t}\n\nfunction pubkey_to_address($pubkey)\n\t{\n\t\treturn hash160_to_address(hash160($pubkey));\n\t}\n\n// Bech32\nfunction bech32_polymod($values) {\n    // Internal function that computes the Bech32 checksum.\n    $generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n\n    $chk = 1;\n    foreach ($values as $value) {\n        $top = $chk >> 25;\n        $chk = ($chk & 0x1ffffff) << 5 ^ $value;\n        for ($i=0; $i<5; $i++) {\n            if (($top >> $i) & 1 == 1) {\n                $chk ^= $generator[$i];\n            }\n        }\n    }\n\n    return $chk;\n}\n\nfunction bech32_hrp_expand($hrp) {\n    // Expand the HRP in to values for checksum computation.\n    $expand1 = [];\n    $expand2 = [];\n    foreach (str_split($hrp) as $c) {\n        $expand1[] = ord($c) >> 5; // ord char, right shifted\n        $expand2[] = ord($c) & 31;\n    }\n\n    return array_merge($expand1, [0], $expand2);\n}\n\nfunction bech32_create_checksum($hrp, $data) {\n    // Compute the checksum values given HRP and data.\n    $values = array_merge(bech32_hrp_expand($hrp), $data);\n    $polymod = bech32_polymod(array_merge($values, [0, 0, 0, 0, 0, 0])) ^ 1;\n\n    $checksum = [];\n    for ($i=0; $i<6; $i++) {\n        $checksum[] = ($polymod >> 5 * (5 - $i)) & 31;\n    }\n\n    return $checksum;\n}\n\nfunction convertbits($data, $from, $to, $pad=true) {\n    // General power-of-2 base conversion.\n    // This is used to prepare a scriptpubkey ready for bech32 encoding.\n    $acc    = 0;\n    $bits   = 0;\n    $ret    = [];\n    $maxv   = (1 << $to) - 1;               // 0b100000 (31)\n    $maxacc = (1 << ($from + $to - 1)) - 1; // 0b111111111111 (4095)\n\n    foreach ($data as $value) {\n        if ($value < 0 || ($value >> $from) != 0) {\n            throw new Bech32Exception(\"Invalid data range for converting bits.\");\n        }\n\n        $acc = (($acc << $from) | $value) & $maxacc;\n        $bits += $from;\n        while ($bits >= $to) {\n            $bits -= $to;\n            $ret[] = ($acc >> $bits) & $maxv;\n        }\n    }\n\n    if ($pad) {\n        if ($bits) {\n            $ret[] = ($acc << ($to - $bits)) & $maxv;\n        }\n        elseif ($bits >= $from || (($acc << ($to - $bits)) & $maxv)) {\n            throw new Bech32Exception(\"Invalid data.\");\n\n        }\n    }\n\n    return $ret;\n}\n\nfunction bech32_encode($hrp, $data) {\n    // Compute a Bech32 string given HRP and data values.\n\n    // Settings\n    $separator = '1'; // always 1\n    $charset = ['q', 'p', 'z', 'r', 'y', '9', 'x', '8', 'g', 'f', '2', 't', 'v', 'd', 'w', '0', 's', '3', 'j', 'n', '5', '4', 'k', 'h', 'c', 'e', '6', 'm', 'u', 'a', '7', 'l'];\n\n    // Create the checksum from the data\n    $checksum = bech32_create_checksum($hrp, $data);\n\n    // Convert data + checksum to Bech32\n    $combined = array_merge($data, $checksum);\n\n    $base32 = [];\n    foreach ($combined as $d) {\n        $base32[] = $charset[$d];\n    }\n\n    // Return Bech32 string\n    return $hrp . $separator . implode('', $base32);\n    // human readable | separator | bech32 data (with checksum)\n\n}\n\nfunction bech32_address($scriptpubkey) {\n    // Convert scriptpubkey to a Bech32 address.\n\n    // Convert hex scriptpubkey to 8-bit integer values\n    $values = unpack(\"C*\", pack(\"H*\", $scriptpubkey));\n\n    // Get the version and witness program bytes\n    // |00|14|751e76e8199196d454941c45d1b3a323f1433bd6\n    $version = array_slice($values, 0, 1);\n    $push = array_slice($values, 1, 1); // not needed\n    $program = array_slice($values, 2); // must be in 5-bit groups...\n\n    // Create address\n    $programconv = convertbits($program, 8, 5); // 5-bit groups\n    $data = array_merge($version, $programconv);\n    $bech32 = bech32_encode(\"bc\", $data);\n\n    return $bech32;\n    // |hrp|sep|data                             [chk ]|\n    //  bc  1   qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4\n}\n"
  },
  {
    "path": "functions/readtx.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once \"functions/basic.php\";\n\nfunction readtx($transactions, $p=0) {\n\n\t// Start Storing\n\t$txbuffer = ''; // clear the tx buffer, ready to start storing a tx data\n\t\n\t// version (4 bytes)\n\t$txbuffer .= substr($transactions, $p, 8); $p+=8;\n\n\t// if segwit [00][01]\n\tif (hexdec(substr($transactions, $p, 2)) == 0 && hexdec(substr($transactions, $p+2, 2)) > 0) {\n\t\t$segwit = true;\n\t\t$txbuffer .= substr($transactions, $p, 4); $p+=4; // take the [marker][flag] and move on\n\t}\n\telse {\n\t\t$segwit = false;\n\t}\n\n\t// inputs\n\tlist($full, $value, $len) = varInt(substr($transactions, $p));\n\t$txbuffer .= $full; $p+=$len; // inputcount (varint)\n\t$inputcount = $value;\n\t\n\tfor ($i=1; $i<=$inputcount; $i++) {\n\t\t$txbuffer .= substr($transactions, $p, 64); $p+=64; // txid (32 bytes)\n\t\t$txbuffer .= substr($transactions, $p, 8); $p+=8; // vout (4 bytes)\n\t\tlist($full, $value, $len) = varInt(substr($transactions, $p)); // (varint)\n\t\t$txbuffer .= $full; $p+=$len; // scriptSig size\n\t\t$size = $value*2; // number of chars\n\t\t$txbuffer .= substr($transactions, $p, $size); $p += $size; // scriptSig\n\t\t$txbuffer .= substr($transactions, $p, 8); $p+=8; // sequence\n\t}\n\n\t// outputs\n\tlist($full, $value, $len) = varInt(substr($transactions, $p));\n\t$txbuffer .= $full; $p+=$len; // outputcount (varint)\n\t$outputcount = $value;\n\n\tfor ($i=1; $i<=$outputcount; $i++) {\n\t\t$txbuffer .= substr($transactions, $p, 16); $p+=16; // value (8 bytes)\n\t\tlist($full, $value, $len) = varInt(substr($transactions, $p)); // (varint)\n\t\t$txbuffer .= $full; $p+=$len; // scriptPubKeysize\n\t\t$size = $value*2; //  number of chars\n\t\t$txbuffer .= substr($transactions, $p, $size); $p += $size; // scriptPubKey\n\t}\n\n\t// get witnesses (if segwit)\n\tif ($segwit) {\n\n\t\t// number of witnesses (same as input count)\n\t\tfor ($i=1; $i<=$inputcount; $i++) {\n\t\t\t\n\t\t\t// number of witness elements\n\t\t\tlist($full, $value, $len) = varInt(substr($transactions, $p)); \n\t\t\t$txbuffer .= $full; $p+=$len;\n\t\t\t$witnesscount = $value;\n\t\t\n\t\t\tfor ($j=1; $j<=$witnesscount; $j++) {\n\t\t\t\t// size of witness\n\t\t\t\tlist($full, $value, $len) = varInt(substr($transactions, $p));\n\t\t\t\t$txbuffer .= $full; $p+=$len;\n\n\t\t\t\t// witness\n\t\t\t\t$size = $value*2;\n\t\t\t\t$txbuffer .= substr($transactions, $p, $size); $p+=$size;\n\t\t\t}\n\t\t}\n\t}\n\n\t// locktime (4 bytes)\n\t$txbuffer .= substr($transactions, $p, 8); $p+=8;\n\n\treturn array($txbuffer, $p);\n\n}\n"
  },
  {
    "path": "functions/script.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'keys.php';\n\nfunction decodeScript($script) {\n\nif($script) {\n\n\t// store the original\n\t$hex = $script;\n\n\t$opcodes = [\n\n\t\t// Constants (number of bytes to push on to stack)\n\t\t// ---------\n\t\t'00' => 'OP_FALSE',\n\t\t// 01-4b = number of bytes to be pushed on to the stack\n\t\t'4c' => 'OP_PUSHDATA1', // next byte = number of bytes to push\n\t\t'4d' => 'OP_PUSHDATA2', // next 2 bytes = number of bytes to push\n\t\t'4e' => 'OP_PUSHDATA4', // next 4 bytes = number of bytes to push\n\t\t'4f' => 'OP_1NEGATE',   // number -1 pushed on to stack\n\t\t'51' => 'OP_1',         // number 1 pushed on to stack\n\t\t'52' => 'OP_2',\n\t\t'53' => 'OP_3',\n\t\t'54' => 'OP_4',\n\t\t'55' => 'OP_5',\n\t\t'56' => 'OP_6',\n\t\t'57' => 'OP_7',\n\t\t'58' => 'OP_8',\n\t\t'59' => 'OP_9',\n\t\t'6a' => 'OP_10',\n\t\t'6b' => 'OP_11',\n\t\t'6c' => 'OP_12',\n\t\t'6d' => 'OP_13',\n\t\t'6e' => 'OP_14',\n\t\t'6f' => 'OP_15',\n\t\t'60' => 'OP_16',\n\t\t// 52-60 = The number in the word name (OP_2-OP_16) is pushed onto the stack.\n\n\t\t// Flow Control\n\t\t// ------------\n\t\t'61' => 'OP_NOP', // does nothing\n\t\t'63' => 'OP_IF',\n\t\t'64' => 'OP_NOTIF',\n\t\t'67' => 'OP_ELSE',\n\t\t'68' => 'OP_ENDIF',\n\t\t'69' => 'OP_VERIFY',\n\t\t'6a' => 'OP_RETURN',\n\n\t\t// Stack\n\t\t// -----\n\t\t'6b' => 'OP_TOALTSTACK',\n\t\t'6c' => 'OP_FROMALTSTACK',\n\t\t'73' => 'OP_IFDUP',\n\t\t'74' => 'OP_DEPTH',\n\t\t'75' => 'OP_DROP', // Removes the top stack item.\n\t\t'76' => 'OP_DUP',\n\t\t'77' => 'OP_NIP',\n\t\t'78' => 'OP_OVER',\n\t\t'79' => 'OP_PICK',\n\t\t'7a' => 'OP_ROLL',\n\t\t'7b' => 'OP_ROT',\n\t\t'7c' => 'OP_SWAP',\n\t\t'7d' => 'OP_TUCK',\n\t\t'6d' => 'OP_2DROP',\n\t\t'6e' => 'OP_2DUP',\n\t\t'6f' => 'OP_3DUP',\n\t\t'70' => 'OP_2OVER',\n\t\t'71' => 'OP_2ROT',\n\t\t'72' => 'OP_2SWAP',\n\n\t\t// Splice\n\t\t// ------\n\t\t'7e' => 'OP_CAT',\n\t\t'7f' => 'OP_SUBSTR',\n\t\t'80' => 'OP_LEFT',\n\t\t'81' => 'OP_RIGHT',\n\t\t'82' => 'OP_SIZE',\n\n\t\t// Bitwise Logit\n\t\t// -------------\n\t\t'83' => 'OP_INVERT',\n\t\t'84' => 'OP_AND',\n\t\t'85' => 'OP_OR',\n\t\t'86' => 'OP_XOR',\n\t\t'87' => 'OP_EQUAL', // Returns 1 if the inputs are exactly equal, 0 otherwise.\n\t\t'88' => 'OP_EQUALVERIFY',\n\n\t\t// Arithmetic\n\t\t// ----------\n\t\t'8b' => 'OP_1ADD',\n\t\t'8c' => 'OP_1SUB',\n\t\t'8d' => 'OP_2MUL',\n\t\t'8e' => 'OP_2DIV',\n\t\t'8f' => 'OP_NEGATE',\n\t\t'90' => 'OP_ABS', // The input is made positive.\n\t\t'91' => 'OP_NOT',\n\t\t'92' => 'OP_0NOTEQUAL',\n\t\t'93' => 'OP_ADD', // a is added to b\n\t\t'94' => 'OP_SUB',\n\t\t'95' => 'OP_MUL',\n\t\t'96' => 'OP_DIV',\n\t\t'97' => 'OP_MOD',\n\t\t'98' => 'OP_LSHIFT',\n\t\t'99' => 'OP_RSHIFT',\n\t\t'9a' => 'OP_BOOLAND',\n\t\t'9b' => 'OP_BOOLOR',\n\t\t'9c' => 'OP_NUMEQUAL',\n\t\t'9d' => 'OP_NUMEQUALVERIFY',\n\t\t'9e' => 'OP_NUMNOTEQUAL',\n\t\t'9f' => 'OP_LESSTHAN',\n\t\t'a0' => 'OP_GREATERTHAN',\n\t\t'a1' => 'OP_LESSTHANOREQUAL',\n\t\t'a2' => 'OP_GREATERTHANOREQUAL',\n\t\t'a3' => 'OP_MIN',\n\t\t'a4' => 'OP_MAX',\n\t\t'a5' => 'OP_WITHIN',\n\n\t\t// Crypto\n\t\t// ------\n\t\t'a6' => 'OP_RIPEMD160',\n\t\t'a7' => 'OP_SHA1',\n\t\t'a8' => 'OP_SHA256',\n\t\t'a9' => 'OP_HASH160',\n\t\t'aa' => 'OP_HASH256',\n\t\t'ab' => 'OP_CODESEPARATOR',\n\t\t'ac' => 'OP_CHECKSIG',\n\t\t'ad' => 'OP_CHECKSIGVERIFY',\n\t\t'ae' => 'OP_CHECKMULTISIG',\n\t\t'af' => 'OP_CHECKMULTISIGVERIFY',\n\n\t\t// Locktime\n\t\t'b1' => 'OP_CHECKLOCKTIMEVERIFY',\n\t\t'b2' => 'OP_CHECKSEQUENCEVERIFY',\n\n\t\t// Pseudo-Words\n\t\t'fd' => 'OP_PUBKEYHASH',\n\t\t'fe' => 'OP_PUBKEY',\n\t\t'ff' => 'OP_INVALIDOPCODE',\n\n\t\t// Reserved Words\n\t\t'50' => 'OP_RESERVED',\n\t\t'62' => 'OP_VER',\n\t\t'65' => 'OP_VERIF',\n\t\t'66' => 'OP_VERNOTIF',\n\t\t'89' => 'OP_RESERVED1',\n\t\t'8a' => 'OP_RESERVED2',\n\t\t'b0' => 'OP_NOP1', // The word is ignored. Does not mark transaction as invalid.\n\t\t'b2' => 'OP_NOP3',\n\t\t'b3' => 'OP_NOP4',\n\t\t'b4' => 'OP_NOP5',\n\t\t'b5' => 'OP_NOP6',\n\t\t'b6' => 'OP_NOP7',\n\t\t'b7' => 'OP_NOP8',\n\t\t'b8' => 'OP_NOP9',\n\t\t'b9' => 'OP_NOP10',\n\n\t];\n\n\t// run through the string, getting the opcodes or specified number of bytes\n\twhile (strlen($script) > 0) {\n\n\t\t// run through every byte (2 characters)\n\t\t$byte = substr($script, 0, 2);\n\n\t\t// store this byte in opcodes array\n\t\t$lockpieces[] = $byte;\n\n\t\t// now remove that byte from the string\n\t\t$script = substr($script, strpos($script, $byte) + strlen($byte));\n\n\t\t// ----------\n\t\t// Push Bytes (0x01 to 0x4e)\n\t\t// ----------\n\t\tif (ctype_xdigit($byte) && hexdec($byte) >= hexdec('00') && hexdec($byte) < hexdec('4e')) {\n\n\t\t\t// 00\n\t\t\tif ($byte == '00') { // Push empty bytes on to stack\n\t\t\t\t$pushbytes = '0';\n\t\t\t}\n\t\t\t// <= 4b\n\t\t\tif (hexdec($byte) >= 1 and hexdec($byte) <= hexdec('4b')) { // $byte indicates the number of bytes\n\t\t\t\t$pushbytes = substr($script, 0, hexdec($byte)*2);\n\t\t\t}\n\n\t\t\t// 4c, 4d, 4e\n\t\t\t$pushers = array(\n\t\t\t\t'4c' => 1,\n\t\t\t\t'4d' => 2,\n\t\t\t\t'4e' => 4,\n\t\t\t);\n\t\t\tif (array_key_exists($byte, $pushers)) {\n\t\t\t\t// get the number of bytes to push\n\t\t\t\t$bytestopush = substr($script, 0, $pushers[$byte]*2);\n\n\t\t\t\t// if no errors\n\t\t\t\tif ($bytestopush) {\n\t\t\t\t\t$script = substr($script, strpos($script, $bytestopush) + strlen($bytestopush)); // remove\n\t\t\t\t\t$pushbytes = substr($script, 0, hexdec($bytestopush)*2);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t$script = NULL;\n\t\t\t\t\t$pushbytes = '[error]';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// pop that opcode off the end of the array and replace it with the specified number of bytes\n\t\t\tarray_pop($lockpieces);\n\t\t\tif ($pushbytes) {\n\t\t\t\t$lockpieces[] = $pushbytes;\n\t\t\t}\n\n\t\t\t// now remove those bytes from the string too\n\t\t\tif ($pushbytes) {\n\t\t\t\t$script = substr($script, strpos($script, $pushbytes) + strlen($pushbytes));\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// convert the hex values to their corresponding opcodes\n\t$i=0;\n\t$lockops = [];\n\tforeach ($lockpieces as $piece) {\n\n\t\t// GET OPCODES\n\n\t\tif (strlen($piece) == 2) {\n\t\t\tif (array_key_exists($piece, $opcodes)) {\n\t\t\t\t$lockops[] = $opcodes[$piece];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$lockops[] = 'OP_???';\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t$lockops[] = $piece;\n\t\t}\n\n\t\t$i++;\n\t}\n\n\n\t// -------------\n\t// GET ADDRESSES\n\t// -------------\n\t$addresses = [];\n\n\tif (count($lockops) > 0) {\n\n\t\t// 1. pubkey (P2PK): <pubkey> OP_CHECKSIG\n\t\tif (count($lockops) == 2) {\n\t\t\tif ($lockops[1] == 'OP_CHECKSIG') {\n\t\t\t\tif (ctype_xdigit($lockops[0]) && (strlen($lockops[0]) == 66 or strlen($lockops[0]) == 130)) {\n\t\t\t\t\t$addresses[] = pubkey_to_address($lockops[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t// 2. pubkeyhash (P2PKH): OP_DUP OP_HASH160 <hash160> OP_EQUALVERIFY OP_CHECKSIG\n\t\tif (count($lockops) == 5) {\n\t\t\tif ($lockops[0] == 'OP_DUP' && $lockops[1] == 'OP_HASH160' && $lockops[3] == 'OP_EQUALVERIFY' && $lockops[4] == 'OP_CHECKSIG') {\n\n\t\t\t\t// check the \"hash160\" is hex and 40 chars\n\t\t\t\tif (ctype_xdigit($lockops[2]) && strlen($lockops[2]) == 40) {\n\t\t\t\t\t$addresses[] = hash160_to_address($lockops[2], '00');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 3. scripthash (P2SH): OP_HASH160 <hash160> OP_EQUAL\n\t\tif (count($lockops) == 3) {\n\t\t\tif ($lockops[0] == 'OP_HASH160' && $lockops[2] == 'OP_EQUAL') {\n\n\t\t\t\t// check the \"hash160\" is hex and 40 chars\n\t\t\t\tif (ctype_xdigit($lockops[1]) && strlen($lockops[1]) == 40) {\n\t\t\t\t\t$addresses[] = hash160_to_address($lockops[1], '05');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 4. <n pubkeys> OP_n OP_CHECKMULTISIG\n\t\tif (array_slice($lockops, -1, 1)[0] == 'OP_CHECKMULTISIG') { // last opcode is op_checkmultisig\n\t\t\tif (substr(array_slice($lockops, -2, 1)[0], 0, 3) == 'OP_') { // second to last begins with OP_\n\t\t\t\t$op_n = preg_replace(\"/[^0-9]/\", '', array_slice($lockops, -2, 1)[0]);\n\t\t\t\t$pubkeys = array_slice($lockops, -2-$op_n, $op_n); // get the expected number of pubkeys\n\t\t\t\tforeach ($pubkeys as $pubkey) {\n\n\t\t\t\t\t// check that it is a pubkey\n\t\t\t\t\t// example error:\n\t\t\t\t\t// OP_2 OP_FALSE 021d69e2b68c3960903b702af7829fadcd80bd89b158150c85c4a75b2c8cb9c394 OP_2 OP_CHECKMULTISIG\n\n\t\t\t\t\tif (ctype_xdigit($pubkey) && (strlen($pubkey) == 66 or strlen($pubkey) == 130)) {\n\t\t\t\t\t\t$addresses[] = pubkey_to_address($pubkey);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t} // if count($lockops) > 0\n\n\t// 5. P2WPKH and P2WSH - 0014{20-bytes} or 0020{32-bytes}\n\t// Use '00' version to identify a native segwit transaction\n\tif (substr($hex, 0, 2) == '00') { // && (substr($hex, 2, 2) == '14' || substr($hex, 2, 2) == '20')) {\n\t\t// |version|push|witnessprogram|\n\t\t//  00      14   751e76e8199196d454941c45d1b3a323f1433bd6\n\t\t//  00      20   88e2e40cd889901733cb2f922be01199d334f3232a34cffee6143482d8eb6c19\n\n\t\t// [ ] Can remove. Just doing an extra check to make sure we haven't already got an address.\n\t\tif (count($addresses) > 0) {\n\t\t\tthrow new Exception(\"Already got an address for what looks like a witness scriptpubkey: \".print_r($addresses));\n\t\t}\n\n\t\t// Determine type\n\t\tif (substr($hex, 2, 2) == '14') { // 20-byte witess program (hash160 of a public key)\n\t\t\t$type = 'P2WPKH';\n\t\t\t$addresses[] = bech32_address($hex);\n\t\t}\n\t\telseif (substr($hex, 2, 2) == '20') { // 32-byte witess program (hash256 of a script)\n\t\t\t$type = 'P2WSH';\n\t\t\t$addresses[] = bech32_address($hex);\n\t\t}\n\t\telse {\n\t\t\tthrow new Exception(\"Unknown witness program size: $hex\");\n\t\t}\n\t}\n\n\t// -------\n\t// RESULT!\n\t// -------\n\t$result = array(\n\t\t'hex' => $hex,\n\t\t'opcodes' => implode(' ', $lockops),\n\t\t'addresses' => implode(', ', $addresses),\n\t);\n}\n\n// if script empty\nelse {\n\t$result = array(\n\t\t'hex' => '',\n\t\t'opcodes' => '',\n\t\t'addresses' => '',\n\t);\n\n}\n\nreturn $result;\n\n}\n\n// test\n// print_r(decodeScript('0201'));\n\n?>\n"
  },
  {
    "path": "functions/tx.php",
    "content": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'basic.php';\ninclude_once 'script.php';\n\nfunction decoderawtransaction($data) {\n\n\t// save the original\n\t$raw = $data;\n\n\t// SegWit\n\tif (hexdec(substr($data, 8, 2)) == 0 && hexdec(substr($data, 10, 2)) > 0) { // numinputs = 0, numoutputs > 0\n\t\t$segwit = true;\n\t\t$array['segwit'] = substr($data, 8, 4);\n\t}\n\telse {\n\t\t$segwit = false;\n\t\t$array['segwit'] = false;\n\t}\n\n\t// version\n\t$version = substr($data, 0, 8);\n\t$array['version'] = hexdec(swapEndian($version));\n\t$data = substr($data, 8);\n\n\n\t// remove segwit flag\n\tif ($segwit) {\n\t\t$data = substr($data, 4);\n\t}\n\n\n\t// inputcount\n\tlist($invarint_full, $invarint_value, $invarint_len) = varInt($data);\n\t// $array['inputcount'] = $invarint_full;\n\t$data = substr($data, $invarint_len);\n\n\t// txins\n\tfor ($i=0; $i<$invarint_value; $i++) {\n\t\t// txids\n\t\t$array['vin'][$i]['txid'] = swapEndian(substr($data, 0, 64));\n\t\t$data = substr($data, 64);\n\n\t\t// vouts\n\t\t$array['vin'][$i]['vout'] = hexdec(swapEndian(substr($data, 0, 8)));\n\t\t$data = substr($data, 8);\n\n\t\t// signaturesizes\n\t\tlist($sigvarint_full, $sigvarint_value, $sigvarint_len) = varInt($data);\n\t\t//$array['signaturesizes'][$i] = $sigvarint_full;\n\t\t$data = substr($data, $sigvarint_len);\n\n\t\t// signatures\n\t\t$signaturelength = 2 * $sigvarint_value;\n\t\t$array['vin'][$i]['scriptSig']['hex'] = substr($data, 0, $signaturelength);\n\t\t$data = substr($data, $signaturelength);\n\n\t\t// sequence\n\t\t$sequence = substr($data, 0, 8);\n\t\t$array['vin'][$i]['sequence'] = hexdec(swapEndian($sequence));\n\t\t$data = substr($data, 8);\n\t}\n\n\t// outputcount\n\tlist($outvarint_full, $outvarint_value, $outvarint_len) = varInt($data);\n\t//$array['outputcount'] = $outvarint_full;\n\t$data = substr($data, $outvarint_len);\n\n\t// txouts\n\tfor ($i=0; $i<$outvarint_value; $i++) {\n\t\t// value\n\t\t$array['vout'][$i]['vout'] = $i;\n\n\t\t// value\n\t\t$array['vout'][$i]['value'] = hexdec(swapEndian(substr($data, 0, 16)));\n\t\t$data = substr($data, 16);\n\n\t\t// locksize\n\t\tlist($lockvarint_full, $lockvarint_value, $lockvarint_len) = varInt($data);\n\t\t//$array['lockingscriptsizes'][$i] = $lockvarint_full;\n\t\t$data = substr($data, $lockvarint_len);\n\n\t\t// lockingscript\n\t\t$lockingscriptlength = 2 * $lockvarint_value;\n\t\t$lockingscript = substr($data, 0, $lockingscriptlength);\n\t\t$array['vout'][$i]['scriptPubKey'] = decodeScript($lockingscript);\n\t\t$data = substr($data, $lockingscriptlength);\n\n\t}\n\n\tif ($segwit) {\n\n\t\t$witnessdata = ''; // start storing all witness data, so it can be subtracted from full data to get the original txid\n\n\t\t// for each input\n\t\tfor ($i=0; $i<$invarint_value; $i++) {\n\n\t\t\t$witnesshex = ''; // store individual input's witness hex data\n\t\t\t// 02\n\t\t\t// 48 3045...901\n\t\t\t// 21 0382...0ac\n\n\t\t\t// number of witness elements\n\t\t\tlist($witvarint_full, $witvarint_value, $witvarint_len) = varInt($data);\n\t\t\t$witnesshex .= $witvarint_full;\n\t\t\t$data = substr($data, $witvarint_len);\n\n\t\t\tfor ($j=0; $j<$witvarint_value; $j++) {\n\n\t\t\t\t// witnessesizes\n\t\t\t\tlist($witsizevarint_full, $witsizevarint_value, $witsizevarint_len) = varInt($data);\n\t\t\t\t$witnesshex .= $witsizevarint_full;\n\t\t\t\t$data = substr($data, $witsizevarint_len);\n\n\t\t\t\t// witnesses\n\t\t\t\t$witnesslength = 2 * $witsizevarint_value;\n\t\t\t\t$array['vin'][$i]['witness'][$j] = substr($data, 0, $witnesslength);\n\t\t\t\t$witnesshex .= substr($data, 0, $witnesslength);\n\t\t\t\t$data = substr($data, $witnesslength);\n\n\t\t\t}\n\n\t\t\t$array['vin'][$i]['witness']['hex'] = $witnesshex;\n\t\t\t$witnessdata .= $witnesshex;\n\n\t\t}\n\n\t}\n\n\n\t// locktime\n\t$locktime = substr($data, 0, 8);\n\t$array['locktime'] = hexdec(swapEndian($locktime));\n\t$data = substr($data, 8);\n\n\n\t// TXID\n\tif ($segwit) {\n\t\t// wtxid\n\t\t$wtxid = hash(\"sha256\", pack('H*', $raw));\n\t\t$wtxid = hash(\"sha256\", pack('H*', $wtxid));\n\t\t$array['wtxid'] = swapEndian($wtxid);\n\n\t\t// original txid (remove flag and witness data)\n\t\t$withoutflag = substr($raw, 0, 8).substr($raw, 12); // remove flag\n\t\t$txid_orig = str_replace($witnessdata, '', $withoutflag); // remove witness data\n\n\t\t$txid = hash(\"sha256\", pack('H*', $txid_orig));\n\t\t$txid = hash(\"sha256\", pack('H*', $txid));\n\t\t$array['txid'] = swapEndian($txid);\n\t}\n\telse {\n\t\t$txid = hash(\"sha256\", pack('H*', $raw));\n\t\t$txid = hash(\"sha256\", pack('H*', $txid));\n\t\t$array['txid'] = swapEndian($txid);\n\t}\n\n\t// size\n\t$array['size'] = strlen($raw)/2;\n\n\t// return the PHP array\n\n\treturn $array;\n\n} // end function\n\n?>\n"
  },
  {
    "path": "main.php",
    "content": "<?php\n/*\n * title:   bitcoin-to-neo4j\n * desc:    Import Bitcoin's blk.dat files (the blockchain) in to a Neo4j graph database.\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\n// Config\nrequire_once 'config.php';\n\n// Redis\n$redis = new Redis();\n$redis->connect(REDIS_IP, REDIS_PORT);\n\n// Composer\nrequire_once 'vendor/autoload.php';\n\n// Neo4j\nuse Laudis\\Neo4j\\ClientBuilder; // (neo4j-php/neo4j-php-client)\n\n$neo = ClientBuilder::create()\n    ->withDriver('bolt', 'bolt://'.NEO4J_USER.':'.NEO4J_PASS.'@'.NEO4J_IP.':'.NEO4J_PORT) // creates a bolt driver\n    ->withDefaultDriver('bolt')\n    ->build();\n\n// Check Neo4j is running\ntry {\n    $neo->run(\"SHOW DATABASES\");\n}\ncatch (\\Throwable $th) {\n    echo \"Doesn't look like Neo4j is running or available yet. If you've just started Neo4j, give it a few moments.\".PHP_EOL;\n    exit;\n}\n\n// Create Neo4j constraints (for unique indexes, not regular indexes (should be faster))\n$neo->run(\"CREATE CONSTRAINT IF NOT EXISTS FOR (b:block) REQUIRE b.hash IS UNIQUE\");\n$neo->run(\"CREATE CONSTRAINT IF NOT EXISTS FOR (t:tx) REQUIRE t.txid IS UNIQUE\");\n$neo->run(\"CREATE CONSTRAINT IF NOT EXISTS FOR (o:output) REQUIRE o.index IS UNIQUE\");\n$neo->run(\"CREATE INDEX IF NOT EXISTS FOR (b:block) ON (b.height)\");\n$neo->run(\"CREATE INDEX IF NOT EXISTS FOR (a:address) ON (a.address)\"); // for getting outputs locked to an address\n\n// Cypher Queries\n$cypher['tx']            = file_get_contents(\"cypher/tx.cypher\");\n$cypher['tx-coinbase']   = file_get_contents(\"cypher/tx-coinbase.cypher\");\n$cypher['block']         = file_get_contents(\"cypher/block.cypher\");\n$cypher['block-genesis'] = file_get_contents(\"cypher/block-genesis.cypher\");\n\n// Functions\ninclude('functions/tx.php');        // decode transaction\ninclude('functions/block.php');     // calculate block reward\ninclude('functions/readtx.php');    // read single transaction size quickly\ninclude('cyphertx.php');            // insert tx in to neo4j\n\n// Handy Functions\nfunction blk00000($i): string { return 'blk'.str_pad($i, 5, '0', STR_PAD_LEFT).'.dat'; }\n\n// ---------\n// PRE-CHECK\n// ---------\nif (!file_exists(BLOCKS)) {\n    exit(\"Couldn't find \".BLOCKS.PHP_EOL.\"Make sure you have entered the correct path to Bitcoin's blk*.dat files.\\n\");\n}\n\n// -------------------\n// READ THE BLOCKCHAIN\n//--------------------\n\n$start = $redis->hget('bitcoin-to-neo4j', 'blk.dat') ?: 0; // which blk.dat file to start with\n$startfp = $redis->hget('bitcoin-to-neo4j', 'fp') ?: 0; // Zero if not set\n\nif (!extension_loaded(\"gmp\")) throw new \\Error(\"PHP GMP extension is not installed.\");\n\nwhile(true) { // Keep trying to read files forever\n\n    $file = blk00000($start); // format file number (e.g. blk00420.dat instead of blk420.dat)\n    $path = BLOCKS.\"/$file\";\n\n    $fh = fopen($path, 'rb'); echo \"Reading $path...\\n\\n\"; sleep(1);\n\n    $dat_start = microtime(true); // track how long it takes to import a blk.dat file\n    $b = 1; // for counting the blocks in each file\n\n    // keep track of which blk.dat file we are on (store it in Redis)\n    $redis->hset('bitcoin-to-neo4j', 'blk.dat', $start);\n\n    while(true) { // Read through a blk*.dat file\n\n        // pick up from where we left off\n        if (isset($startfp)) { fseek($fh, $startfp); unset($startfp); }\n\n        // keep track of where the file pointer is (before each block).\n        $fp = ftell($fh);\n\n        // store file pointer in redis (only after a block has been fully ran through)\n        $redis->hset('bitcoin-to-neo4j', 'fp', $fp);\n\n        // =====\n        // BLOCK\n        // =====\n        $b_start = microtime(true); // track how long it takes to import a block\n\n        // 1. Read one byte at a time until we hit a block header (magic bytes)\n        $buffer = '';\n        $bytesread = 0;\n        while (true) {\n\n            // Read 1 byte at a time\n            $buffer .= bin2hex(fread($fh, 1));\n            $bytesread++;\n            $buffer = substr($buffer, -8); // magic bytes is 4 bytes\n\n            // Magic Bytes\n            $magicbytes = TESTNET ? '0b110907' : 'f9beb4d9';\n\n            if (strlen($buffer) == 8) {\n                // hit a block header\n                if ($buffer == $magicbytes) {\n                    $blocksize = fread($fh, 4);\n                    $blocksize = hexdec(swapEndian(bin2hex($blocksize)));\n\n                    // Read the full block of data\n                    $block = bin2hex(fread($fh, $blocksize));\n\n                    // if last 500 characters are all zeros, then we probably haven't got the full block data, so wait for it\n                    if (hexdec(substr($block, -500)) == 0) {\n                        echo \"Doesn't look like the blk.dat file has all the bytes of data for the block. Wait a second for it to arrive...\\n\";\n                        file_put_contents('log/blockwait.txt', \"$block\\n\\n\");\n\n                        // wait a second\n                        sleep(1);\n\n                        // go back to end of last block\n                        fseek($fh, $fp);\n                        $fp = ftell($fh);\n                        $bytesread = 0;     // reset bytes read\n\n                        // go back to start of loop and try reading block again\n                        continue;\n                    }\n                    else {\n                        // reset buffer\n                        $buffer = '';\n\n                        // break out and start reading transactions\n                        break;\n                    }\n\n                }\n                // if we do not hit a block header\n                else {\n                    // if we have read forward another 1000 bytes and not found another magic bytes\n                    if ($bytesread > 1000) {\n\n                        // go back to end of last block\n                        fseek($fh, $fp);\n                        $fp = ftell($fh);\n\n                        // reset bytes read\n                        $bytesread = 0;\n                        sleep(1);\n\n                        echo \"Doesn't look like there's another block yet. Re-reading... ($fp)\\n\";\n                    }\n                }\n            }\n\n\n            // hit end of file\n            if (feof($fh)) {\n\n                // if there is a next file, go to it\n                $nextfile = blk00000($start+1);\n                if (file_exists(BLOCKS.\"/$nextfile\")) {\n                    echo \"\\nThere is a file $nextfile.\\n\"; sleep(1);\n                    $start = $start+1;  // Set the file number to the next one\n                    break 2;            // ... Restart main loop (opens next file)\n                }\n\n            }\n        }\n\n\n        // Block Header (human format)\n        $version =      hexdec(swapEndian(substr($block, 0, 8)));\n        $prevblock =    swapEndian(substr($block, 8, 64)); // searchable byte order\n        $merkleroot =   swapEndian(substr($block, 72, 64));\n        $timestamp =    hexdec(swapEndian(substr($block, 136, 8)));\n        $bits =         swapEndian(substr($block, 144, 8));\n        $nonce =        hexdec(swapEndian(substr($block, 152, 8)));\n\n\n        // i. Work out this block's hash\n        $blockheader = substr($block, 0, 160); // header is 80 bytes total\n        $blockhash = swapEndian(hash('sha256', hash('sha256', hex2bin($blockheader), true)));\n        $hash = $blockhash; // this is for possibly setting the tip height in redis\n\n        // a. Number of upcoming transactions (varint)\n        $varint = substr($block, 160); list($full, $value, $len) = varInt($varint);\n        $txcount = $value;\n\n        $transactions = substr($block, 160+$len); // +$len: start from the end of the length of the tx count varint\n\n        // 3. Save Block\n        $b_start = microtime(true);\n        $blocksizekb = number_format($blocksize/1000, 2);\n        echo \" $b: $blockhash [$blocksizekb kb] (fp:$fp) \";\n\n        // Select Cypher Query\n        if ($prevblock == '0000000000000000000000000000000000000000000000000000000000000000') { // Genesis Block\n            $query = $cypher['block-genesis'];\n        }\n        else {\n            $query = $cypher['block'];\n        }\n\n        // Save this block to Neo4j\n        $run = $neo->run($query,\n        [\n            'blockhash'  => $blockhash,\n            'blocksize'  => $blocksize,\n            'txcount'    => $txcount,\n            'version'    => $version,\n            'prevblock'  => $prevblock,\n            'merkleroot' => $merkleroot,\n            'timestamp'  => $timestamp,\n            'bits'       => $bits,\n            'nonce'      => $nonce\n        ]\n        );\n\n        // ------------------\n        // HEIGHT BASED STUFF\n        // ------------------\n\n        // Get the height\n        foreach ($run as $record) {\n            $height = $record->get('height');\n            echo $height;\n            $prevblock = $record->get('prevblock');\n        }\n        // If we have a height for this block, set value for coinbase input.\n        if ($height !== NULL) {\n            $blockreward = calculateBlockReward($height);\n\n            $neo->run('\n            MATCH (block :block {hash:$blockhash})-[:coinbase]->(coinbase :output:coinbase)\n            SET coinbase.value=$blockreward\n            ',\n            [\n                'blockhash' => $blockhash,\n                'blockreward' => $blockreward,\n            ]\n            );\n\n        }\n\n        // If we don't have a height, save this block hash for future updating\n        else {\n            echo \"\\n  This block's prevblock is not in database. Saving it.\\n\";\n\n            // save preblock->blockhash to redis\n            $redis->hset(\"bitcoin-to-neo4j:orphans\", $prevblock, $blockhash);\n\n            // print out how many orphan blocks we have saved in Redis\n            echo '  - blocks needed = '.$redis->hlen('bitcoin-to-neo4j:orphans').\"\\n\";\n        }\n\n        // ----------\n        // ORPHAN RUN\n        // ----------\n\n        // If we've got a prevblock for a block with no height (and has a height for populating blocks above it)\n        if ($redis->hExists('bitcoin-to-neo4j:orphans', $blockhash) && $height !== NULL) {\n            echo \"\\n  Parent block! Updating block height, coinbase values and coinbase tx fees for blocks above it...\\n\";\n\n            // Get all the blocks that are chained to this one (above it)\n            $chainabove = $neo->run('\n            MATCH (dependency :block {hash:$blockhash})<-[:chain*]-(blocks :block)\n            RETURN collect(blocks.hash) as chainabove\n            ',\n            [\n                'blockhash' => $blockhash\n            ]\n            );\n\n            // Get the array of blocks to be populated\n            foreach ($chainabove as $record) {\n                $chainabove = $record->get('chainabove');\n            };\n\n            $heights = array();\n            // Set height for each of these blocks\n            foreach ($chainabove as $orphan) {\n                echo \"    $orphan \";\n\n                $orphanrun = $neo->run('\n                MATCH (block :block {hash:$orphan})-[:chain]->(prevblock :block)\n                SET block.height=prevblock.height+1\n                RETURN block\n                ',\n                [\n                    'orphan' => $orphan,\n                ]\n                );\n\n                foreach ($orphanrun as $record) {\n                    $orphanblock = $record->get('block');\n                }\n                $orphanheight = $orphanblock->properties()->get('height');\n                $orphanprevblock = $orphanblock->properties()->get('prevblock');\n\n                echo \"$orphanheight\\n\";\n\n                // Set the coinbase values based on the height (can also set the fee now we know the block reward)\n                $blockreward = calculateBlockReward($orphanheight);\n\n                // Update coinbase and fee (if the coinbase input value has not been set)\n                $coinbaserun = $neo->run('\n                MATCH (block:block {hash:$orphan})-[:coinbase]->(coinbase:output:coinbase)-[:in]->(tx:tx)\n                WHERE coinbase.value IS NULL\n                SET coinbase.value = $blockreward\n                SET tx.fee = tx.fee + $blockreward\n                ',\n                [\n                    'orphan'      => $orphan,\n                    'blockreward' => $blockreward,\n                ]\n                );\n\n                // Keep log of heights that have been added\n                $heights[$orphan] = $orphanheight;\n\n                // Remove block from redis orphans\n                $redis->hdel(\"bitcoin-to-neo4j:orphans\", $orphan);\n\n            }\n\n            // Remove this current block from redis orphan too\n            $redis->hdel(\"bitcoin-to-neo4j:orphans\", $blockhash);\n\n            // Find the max height and hash we've managed to get\n            asort($heights);\n            $max = array_slice($heights, -1, 1);\n            $hash = key($max);\n            $height = $max[$hash];\n\n        }\n\n        // Store longest known blockchain height in Redis\n        if ($height > $redis->hget(\"bitcoin-to-neo4j:tip\", 'height')) {\n            $redis->hset(\"bitcoin-to-neo4j:tip\", 'height', $height);\n            $redis->hset(\"bitcoin-to-neo4j:tip\", 'hash', $hash);\n        }\n\n\n        // ============\n        // TRANSACTIONS\n        // ============\n        echo \"\\n  $txcount\\n\";\n\n        // Read Individual Transactions\n\n        // 1. Read each transaction in this string of transactions\n        $p = 0; // pointer\n        $t = 1; // tx count\n        while (isset($transactions[$p])) { // continue until end of string of transactions\n            // store the current pointer in case we need to go back to it\n            $pbefore = $p;\n\n            // read one tx (give a start pointer and it returns end pointer)\n            list($transaction, $p) = readtx($transactions, $p);\n\n            // get the txid ready so that it can be used in error handler\n            $txid = swapEndian(hash('sha256', hash('sha256', hex2bin($transaction), true)));\n\n            // ----------------\n            // CYPHER TX INSERT\n            // ----------------\n            $tx_start =  microtime(true);\n            cypherTx($neo, $transaction, $t, $blockhash, $cypher); // IMPORT THE TRANSACTION IN TO NEO4J! (using functions/cyphertx.php)\n            $tx_time = microtime(true)-$tx_start;\n\n            // Display the time it took to insert transaction\n            echo '  '.number_format($tx_time, 5).\"\\n\";\n\n            // next tx...\n            $t++;\n\n        } // transaction block string loop\n\n\n        $b_end = microtime(true);\n        echo '  '.number_format(($b_end-$b_start)/60, 5).\" mins \\n\\n\";\n\n        // next block...\n        $b++; // update block count for this blk.dat file\n\n    } // blk*.dat loop\n\n    // log that the file has been done\n    $dat_end = microtime(true); $dat_time = number_format(($dat_end-$dat_start)/60, 2);\n    $b--;\n    $redis->hset('bitcoin-to-neo4j:log', $file, \"[$b] $dat_time mins\");\n\n\n} // Infinite Loop\n"
  }
]