[
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [tgalal]\n"
  },
  {
    "path": ".gitignore",
    "content": "# Created by https://www.gitignore.io/api/windows,linux,osx,python,vim\n\n### Windows ###\n# Windows image file caches\nThumbs.db\nehthumbs.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n\n\n### Linux ###\n*~\n\n# KDE directory preferences\n.directory\n\n# Linux trash folder which might appear on any partition or disk\n.Trash-*\n\n\n### OSX ###\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\r\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n\n### Python ###\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*,cover\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n\n### Vim ###\n[._]*.s[a-w][a-z]\n[._]s[a-w][a-z]\n*.un~\nSession.vim\n.netrwhist\n*~\n\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: python\npython: '3.7'\n# command to install dependencies\n\nenv:\n  global:\n    - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so\n    - SEGFAULT_SIGNALS=all\n  matrix:\n    - TOXENV=py26\n    - TOXENV=py27\n    - TOXENV=py32\n    - TOXENV=py33\n    - TOXENV=py35\n    - TOXENV=py36\n    - TOXENV=py37\nbefore_install:\n  - python --version\n  - uname -a\n  - lsb_release -a\ninstall:\n  - pip install tox\n  - virtualenv --version\n  - easy_install --version\n  - pip --version\n  - tox --version\n# command to run tests\nscript:\n  - tox -v\nafter_failure:\n  - more .tox/log/* | cat\n  - more .tox/*/log/* | cat\nbefore_cache:\n  - rm -rf $HOME/.cache/pip/log\ncache:\n  directories:\n    - $HOME/.cache/pip\nbranches:\n  only:\n    - master\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The 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 to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When 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\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For 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\n  Developers 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\n  For 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\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, 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 to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The 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 of\nworks, 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\n  To \"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 an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"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\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the 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\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"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\n  The \"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\n  The \"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\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All 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\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No 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\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You 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\n  You 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\n  You 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 conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\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\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\n  A 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\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\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\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\n    Corresponding Source from a network server at no charge.\n\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\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\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A 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\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If 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\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding 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\n  When 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\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat 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\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\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All 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\n  If 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\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You 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\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, 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\n  Termination 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\n  You are not required to accept this License in order to receive or\nrun a 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\n  Each 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\n  An \"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\n  You 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\n  A \"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\n  A contributor's \"essential patent claims\" are all patent claims\nowned or 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\n  Each 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\n  In 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\n  If 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\n  If, 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\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing 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\n  If 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 this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding 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\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later 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\n  THERE 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 WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If 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\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If 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 terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"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 mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\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 appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "README.md",
    "content": "This is a python port of [libsignal-protocol-java](https://github.com/WhisperSystems/libaxolotl-android) originally written by [Moxie Marlinspike](https://github.com/moxie0)\n\nOverview from original author's:\n\n > This is a ratcheting forward secrecy protocol that works in synchronous and asynchronous messaging environments.\n \n# Installation\n\nThe library has some dependencies which are automatically pulled and installed if you use the instructions below for your OS\n\n - [protobuf 3.0+](https://github.com/google/protobuf/)\n - [cryptography](https://cryptography.io)\n - [python-axolotl-curve25519](https://github.com/tgalal/python-axolotl-curve25519)\n\n## Linux\n\nYou need to have python headers installed, usually through installing a package called `python-dev`, then as superuser run:\n```\npython setup.py install\n```\n\n## Windows\n\n - Install [mingw](http://www.mingw.org/) compiler\n - Add mingw to your PATH\n - In PYTHONPATH\\Lib\\distutils create a file called distutils.cfg and add these lines:\n \n```\n[build]\ncompiler=mingw32\n```\n\n - Install gcc: ```mingw-get.exe install gcc```\n - Install [zlib](http://www.zlib.net/)\n - ```python setup.py install```\n\n\n# Usage\n\nThis python port is done in an almost 1:1 mapping to the original java code. Therefore any original documentation for the java code can be easily mapped and used with this python port.\n\n## Install time\n\nAt install time, a libaxolotl client needs to generate its identity keys, registration id, and\nprekeys.\n\n```python\n    identityKeyPair = KeyHelper.generateIdentityKeyPair()\n    registrationId  = KeyHelper.generateRegistrationId()\n    preKeys         = KeyHelper.generatePreKeys(startId, 100)\n    lastResortKey   = KeyHelper.generateLastResortKey()\n    signedPreKey    = KeyHelper.generateSignedPreKey(identityKeyPair, 5)\n\n    #Store identityKeyPair somewhere durable and safe.\n    #Store registrationId somewhere durable and safe.\n\n    #Store preKeys in PreKeyStore.\n    #Store signed prekey in SignedPreKeyStore.\n```\n\n## Building a session\n\nA libaxolotl client needs to implement four interfaces: IdentityKeyStore, PreKeyStore, \nSignedPreKeyStore, and SessionStore.  These will manage loading and storing of identity, \nprekeys, signed prekeys, and session state.\n\nOnce those are implemented, building a session is fairly straightforward:\n\n```python\nsessionStore      = MySessionStore()\npreKeyStore       = MyPreKeyStore()\nsignedPreKeyStore = MySignedPreKeyStore()\nidentityStore     = MyIdentityKeyStore()\n\n# Instantiate a SessionBuilder for a remote recipientId + deviceId tuple.\nsessionBuilder = SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,\n                                                   identityStore, recipientId, deviceId)\n\n# Build a session with a PreKey retrieved from the server.\nsessionBuilder.process(retrievedPreKey)\n\nsessionCipher = SessionCipher(sessionStore, recipientId, deviceId)\nmessage       = sessionCipher.encrypt(\"Hello world!\")\n\ndeliver(message.serialize())\n```\n\n# Examples\n\npython-axolotl is actively used in [yowsup](https://github.com/tgalal/yowsup) to support E2E encryption of WhatsApp\n\n# License\n\nLicensed under the GPLv3: http://www.gnu.org/licenses/gpl-3.0.html\n"
  },
  {
    "path": "axolotl/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n__version__ = '0.2.3'\n__author__ = 'Tarek Galal'\n__email__ = 'tare2.galal@gmail.com'\n__license__ = 'GPLv3'\n__status__ = 'Production'\n"
  },
  {
    "path": "axolotl/axolotladdress.py",
    "content": "class AxolotlAddress(object):\n    def __init__(self, name, deviceId):\n        self.name = name\n        self.deviceId = deviceId\n\n    def getName(self):\n        return self.name\n\n    def getDeviceId(self):\n        return self.deviceId\n\n    def __str__(self):\n        return \"%s;%s\" % (self.name, self.deviceId)\n\n    def __eq__(self, other):\n        if other is None:\n            return False\n\n        if other.__class__ != AxolotlAddress:\n            return False\n\n        return self.name == other.getName() and self.deviceId == other.getDeviceId()\n\n    def __hash__(self):\n        return hash(self.name) ^ self.deviceId\n"
  },
  {
    "path": "axolotl/duplicatemessagexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass DuplicateMessageException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/ecc/__init__.py",
    "content": ""
  },
  {
    "path": "axolotl/ecc/curve.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport os\n\nfrom .eckeypair import ECKeyPair\nfrom ..invalidkeyexception import InvalidKeyException\n\nimport axolotl_curve25519 as _curve\n\n\nclass Curve:\n    DJB_TYPE = 5\n    # always DJB curve25519 keys\n\n    @staticmethod\n    def generatePrivateKey():\n        rand = os.urandom(32)\n        return _curve.generatePrivateKey(rand)\n\n    @staticmethod\n    def generatePublicKey(privateKey):\n        return _curve.generatePublicKey(privateKey)\n\n    @staticmethod\n    def generateKeyPair():\n        from .djbec import DjbECPublicKey, DjbECPrivateKey\n\n        privateKey = Curve.generatePrivateKey()\n        publicKey = Curve.generatePublicKey(privateKey)\n        return ECKeyPair(DjbECPublicKey(publicKey), DjbECPrivateKey(privateKey))\n\n    @staticmethod\n    def decodePoint(_bytes, offset=0):\n        type = _bytes[0]  # byte appears to be automatically converted to an integer??\n\n        if type == Curve.DJB_TYPE:\n            from .djbec import DjbECPublicKey\n\n            type = _bytes[offset] & 0xFF\n            if type != Curve.DJB_TYPE:\n                raise InvalidKeyException(\"Unknown key type: %s \" % type)\n            keyBytes = _bytes[offset+1:][:32]\n            return DjbECPublicKey(bytes(keyBytes))\n        else:\n            raise InvalidKeyException(\"Unknown key type: %s\" % type)\n\n    @staticmethod\n    def decodePrivatePoint(_bytes):\n        from .djbec import DjbECPrivateKey\n        return DjbECPrivateKey(bytes(_bytes))\n\n    @staticmethod\n    def calculateAgreement(publicKey, privateKey):\n        \"\"\"\n        :type publicKey: ECPublicKey\n        :type privateKey: ECPrivateKey\n        \"\"\"\n        if publicKey.getType() != privateKey.getType():\n            raise InvalidKeyException(\"Public and private keys must be of the same type!\")\n\n        if publicKey.getType() == Curve.DJB_TYPE:\n            return _curve.calculateAgreement(privateKey.getPrivateKey(), publicKey.getPublicKey())\n        else:\n            raise InvalidKeyException(\"Unknown type: %s\" % publicKey.getType())\n\n    @staticmethod\n    def verifySignature(ecPublicSigningKey, message, signature):\n        \"\"\"\n        :type ecPublicSigningKey: ECPublicKey\n        :type message: bytearray\n        :type signature: bytearray\n        \"\"\"\n\n        if ecPublicSigningKey.getType() == Curve.DJB_TYPE:\n            result = _curve.verifySignature(ecPublicSigningKey.getPublicKey(), message, signature)\n            return result == 0\n        else:\n            raise InvalidKeyException(\"Unknown type: %s\" % ecPublicSigningKey.getType())\n\n    @staticmethod\n    def calculateSignature(privateSigningKey, message):\n        \"\"\"\n        :type privateSigningKey: ECPrivateKey\n        :type  message: bytearray\n        \"\"\"\n        if privateSigningKey.getType() == Curve.DJB_TYPE:\n            rand = os.urandom(64)\n            res = _curve.calculateSignature(rand, privateSigningKey.getPrivateKey(), message)\n            return res\n        else:\n            raise InvalidKeyException(\"Unknown type: %s\" % privateSigningKey.getType())\n"
  },
  {
    "path": "axolotl/ecc/djbec.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport struct\n\nfrom .ec import ECPublicKey, ECPrivateKey\nfrom ..util.byteutil import ByteUtil\n\n\nclass DjbECPublicKey(ECPublicKey):\n\n    def __init__(self, publicKey):\n        self.publicKey = publicKey\n\n    def serialize(self):\n        from .curve import Curve\n\n        combined = ByteUtil.combine([Curve.DJB_TYPE], self.publicKey)\n        return bytes(combined)\n\n    def getType(self):\n        from .curve import Curve\n\n        return Curve.DJB_TYPE\n\n    def getPublicKey(self):\n        return self.publicKey\n\n    def __eq__(self, other):\n        return self.publicKey == other.getPublicKey()\n\n    def __lt__(self, other):\n        myVal = struct.unpack(\">8i\", self.publicKey)\n        otherVal = struct.unpack(\">8i\", other.getPublicKey())\n\n        return myVal < otherVal\n\n    def __cmp__(self, other):\n        myVal = struct.unpack(\">8i\", self.publicKey)\n        otherVal = struct.unpack(\">8i\", other.getPublicKey())\n\n        if myVal < otherVal:\n            return -1\n        elif myVal == otherVal:\n            return 0\n        else:\n            return 1\n\n\nclass DjbECPrivateKey(ECPrivateKey):\n    def __init__(self, privateKey):\n        self.privateKey = privateKey\n\n    def getType(self):\n        from .curve import Curve\n\n        return Curve.DJB_TYPE\n\n    def getPrivateKey(self):\n        return self.privateKey\n\n    def serialize(self):\n        return self.privateKey\n\n    def __eq__(self, other):\n        return self.privateKey == other.getPrivateKey()\n"
  },
  {
    "path": "axolotl/ecc/ec.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass ECPublicKey(object):\n    __metaclass__ = abc.ABCMeta\n\n    KEY_SIZE = 33\n\n    @abc.abstractmethod\n    def serialize(self):\n        pass\n\n    @abc.abstractmethod\n    def getType(self):\n        pass\n\n\nclass ECPrivateKey(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def serialize(self):\n        pass\n\n    @abc.abstractmethod\n    def getType(self):\n        pass\n"
  },
  {
    "path": "axolotl/ecc/eckeypair.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass ECKeyPair():\n    def __init__(self, publicKey, privateKey):\n        \"\"\"\n        :type publicKey: ECPublicKey\n        :type privateKey: ECPrivateKey\n        \"\"\"\n        self.publicKey = publicKey\n        self.privateKey = privateKey\n\n    def getPrivateKey(self):\n        return self.privateKey\n\n    def getPublicKey(self):\n        return self.publicKey\n"
  },
  {
    "path": "axolotl/groups/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/groups/groupcipher.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..invalidkeyidexception import InvalidKeyIdException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..duplicatemessagexception import DuplicateMessageException\nfrom ..nosessionexception import NoSessionException\nfrom ..protocol.senderkeymessage import SenderKeyMessage\nfrom ..sessioncipher import AESCipher\nfrom ..groups.state.senderkeystore import SenderKeyStore\nclass GroupCipher:\n    def __init__(self, senderKeyStore, senderKeyName):\n        \"\"\"\n        :type senderKeyStore: SenderKeyStore\n        :type senderKeyName: SenderKeyName\n        \"\"\"\n        self.senderKeyStore = senderKeyStore\n        self.senderKeyName = senderKeyName\n\n    def encrypt(self, paddedPlaintext):\n        \"\"\"\n        :type paddedPlaintext: bytes\n        \"\"\"\n        try:\n            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)\n            senderKeyState = record.getSenderKeyState()\n            senderKey = senderKeyState.getSenderChainKey().getSenderMessageKey()\n            ciphertext = self.getCipherText(senderKey.getIv(), senderKey.getCipherKey(), paddedPlaintext)\n\n            senderKeyMessage = SenderKeyMessage(senderKeyState.getKeyId(),\n                                                senderKey.getIteration(),\n                                                ciphertext,\n                                                senderKeyState.getSigningKeyPrivate())\n\n            senderKeyState.setSenderChainKey(senderKeyState.getSenderChainKey().getNext())\n            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)\n\n            return senderKeyMessage.serialize()\n        except InvalidKeyIdException as e:\n            raise NoSessionException(e)\n\n    def decrypt(self, senderKeyMessageBytes):\n        \"\"\"\n        :type senderKeyMessageBytes: bytearray\n        \"\"\"\n        try:\n            record = self.senderKeyStore.loadSenderKey(self.senderKeyName)\n            if record.isEmpty():\n                raise NoSessionException(\"No sender key for: %s\" % self.senderKeyName)\n            senderKeyMessage = SenderKeyMessage(serialized = bytes(senderKeyMessageBytes))\n            senderKeyState = record.getSenderKeyState(senderKeyMessage.getKeyId())\n\n            senderKeyMessage.verifySignature(senderKeyState.getSigningKeyPublic())\n\n            senderKey = self.getSenderKey(senderKeyState, senderKeyMessage.getIteration())\n\n            plaintext = self.getPlainText(senderKey.getIv(), senderKey.getCipherKey(), senderKeyMessage.getCipherText())\n\n            self.senderKeyStore.storeSenderKey(self.senderKeyName, record)\n\n            return plaintext\n        except (InvalidKeyException, InvalidKeyIdException) as e:\n            raise InvalidMessageException(e)\n\n    def getSenderKey(self, senderKeyState, iteration):\n        senderChainKey = senderKeyState.getSenderChainKey()\n\n        if senderChainKey.getIteration() > iteration:\n            if senderKeyState.hasSenderMessageKey(iteration):\n                return senderKeyState.removeSenderMessageKey(iteration)\n            else:\n                raise DuplicateMessageException(\"Received message with old counter: %s, %s\" %\n                                                (senderChainKey.getIteration(), iteration))\n\n        if senderChainKey.getIteration() - iteration > 2000:\n            raise InvalidMessageException(\"Over 2000 messages into the future!\")\n\n        while senderChainKey.getIteration() < iteration:\n            senderKeyState.addSenderMessageKey(senderChainKey.getSenderMessageKey())\n            senderChainKey = senderChainKey.getNext()\n\n        senderKeyState.setSenderChainKey(senderChainKey.getNext())\n        return senderChainKey.getSenderMessageKey()\n\n    def getPlainText(self, iv, key, ciphertext):\n        \"\"\"\n        :type iv: bytearray\n        :type key: bytearray\n        :type ciphertext: bytearray\n        \"\"\"\n        try:\n            cipher = AESCipher(key, iv)\n            plaintext = cipher.decrypt(ciphertext)\n            return plaintext\n        except Exception as e:\n            raise InvalidMessageException(e)\n\n    def getCipherText(self, iv, key, plaintext):\n        \"\"\"\n        :type iv: bytearray\n        :type key: bytearray\n        :type plaintext: bytearray\n        \"\"\"\n        cipher = AESCipher(key, iv)\n        return cipher.encrypt(plaintext)\n"
  },
  {
    "path": "axolotl/groups/groupsessionbuilder.py",
    "content": "# -*- coding: utf-8 -*-\nfrom ..protocol.senderkeydistributionmessage import SenderKeyDistributionMessage\nfrom ..invalidkeyidexception import InvalidKeyIdException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..util.keyhelper import KeyHelper\nclass GroupSessionBuilder:\n    def __init__(self, senderKeyStore):\n        self.senderKeyStore = senderKeyStore\n\n    def process(self, senderKeyName, senderKeyDistributionMessage):\n        \"\"\"\n        :type senderKeyName: SenderKeyName\n        :type senderKeyDistributionMessage: SenderKeyDistributionMessage\n        \"\"\"\n        senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName)\n        senderKeyRecord.addSenderKeyState(senderKeyDistributionMessage.getId(),\n                                          senderKeyDistributionMessage.getIteration(),\n                                          senderKeyDistributionMessage.getChainKey(),\n                                          senderKeyDistributionMessage.getSignatureKey())\n        self.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord)\n\n\n    def create(self, senderKeyName):\n        \"\"\"\n        :type senderKeyName: SenderKeyName\n        \"\"\"\n        try:\n            senderKeyRecord = self.senderKeyStore.loadSenderKey(senderKeyName);\n\n            if senderKeyRecord.isEmpty() :\n                senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(),\n                                                0,\n                                                KeyHelper.generateSenderKey(),\n                                                KeyHelper.generateSenderSigningKey());\n                self.senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);\n\n            state = senderKeyRecord.getSenderKeyState();\n\n            return SenderKeyDistributionMessage(state.getKeyId(),\n                                                state.getSenderChainKey().getIteration(),\n                                                state.getSenderChainKey().getSeed(),\n                                                state.getSigningKeyPublic());\n        except (InvalidKeyException, InvalidKeyIdException) as e:\n            raise AssertionError(e)\n"
  },
  {
    "path": "axolotl/groups/ratchet/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/groups/ratchet/senderchainkey.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport hashlib\nimport hmac\n\nfrom .sendermessagekey import SenderMessageKey\n\n\nclass SenderChainKey:\n    MESSAGE_KEY_SEED = bytearray([0x01])\n    CHAIN_KEY_SEED = bytearray([0x02])\n\n    def __init__(self, iteration, chainKey):\n        \"\"\"\n        :type iteration: int\n        :type chainKey: bytearray\n        \"\"\"\n        self.iteration = iteration\n        self.chainKey = chainKey\n\n    def getIteration(self):\n        return self.iteration\n\n    def getSenderMessageKey(self):\n        return SenderMessageKey(self.iteration, self.getDerivative(self.__class__.MESSAGE_KEY_SEED, self.chainKey))\n\n    def getNext(self):\n        return SenderChainKey(self.iteration + 1, self.getDerivative(self.__class__.CHAIN_KEY_SEED, self.chainKey))\n\n    def getSeed(self):\n        return self.chainKey\n\n    def getDerivative(self, seed, key):\n        mac = hmac.new(bytes(key), bytes(seed), digestmod=hashlib.sha256)\n        return mac.digest()\n"
  },
  {
    "path": "axolotl/groups/ratchet/sendermessagekey.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ...kdf.hkdfv3 import HKDFv3\nfrom ...util.byteutil import ByteUtil\n\n\nclass SenderMessageKey:\n    def __init__(self, iteration, seed):\n        \"\"\"\n        :type iteration: int\n        :type seed: bytearray\n        \"\"\"\n        derivative = HKDFv3().deriveSecrets(seed, \"WhisperGroup\".encode(), 48)\n        parts = ByteUtil.split(derivative, 16, 32)\n\n        self.iteration = iteration\n        self.seed = seed\n        self.iv = parts[0]\n        self.cipherKey = parts[1]\n\n    def getIteration(self):\n        return self.iteration\n\n    def getIv(self):\n        return self.iv\n\n    def getCipherKey(self):\n        return self.cipherKey\n\n    def getSeed(self):\n        return self.seed\n"
  },
  {
    "path": "axolotl/groups/senderkeyname.py",
    "content": "class SenderKeyName(object):\n    def __init__(self, groupId, senderAxolotlAddress):\n        self.groupId = groupId\n        self.sender = senderAxolotlAddress\n\n    def getGroupId(self):\n        return self.groupId\n\n    def getSender(self):\n        return self.sender\n\n    def serialize(self):\n        return \"%s::%s::%s\" % (self.groupId, self.sender.getName(), self.sender.getDeviceId())\n\n    def __eq__(self, other):\n        if other is None: return False\n        if other.__class__ != SenderKeyName: return False\n\n        return self.groupId == other.getGroupId() and self.sender == other.getSender()\n\n    def __hash__(self):\n        return hash(self.groupId) ^ hash(self.sender)\n"
  },
  {
    "path": "axolotl/groups/state/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/groups/state/senderkeyrecord.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ...state.storageprotos_pb2 import SenderKeyRecordStructure\nfrom .senderkeystate import SenderKeyState\nfrom ...invalidkeyidexception import InvalidKeyIdException\n\n\nclass SenderKeyRecord:\n    def __init__(self, serialized=None):\n        self.senderKeyStates = []\n\n        if serialized:\n            senderKeyRecordStructure = SenderKeyRecordStructure()\n            senderKeyRecordStructure.ParseFromString(serialized)\n\n            for structure in senderKeyRecordStructure.senderKeyStates:\n                self.senderKeyStates.append(SenderKeyState(senderKeyStateStructure=structure))\n\n\n    def isEmpty(self):\n        return len(self.senderKeyStates) == 0\n\n    def getSenderKeyState(self, keyId=None):\n        if keyId is None:\n            if len(self.senderKeyStates):\n                return self.senderKeyStates[0]\n            else:\n                raise InvalidKeyIdException(\"No key state in record\")\n        else:\n            for state in self.senderKeyStates:\n                if state.getKeyId() == keyId:\n                    return state\n            raise InvalidKeyIdException(\"No keys for: %s\" % keyId)\n\n    def addSenderKeyState(self, id, iteration, chainKey, signatureKey):\n        \"\"\"\n        :type id: int\n        :type iteration: int\n        :type chainKey: bytearray\n        :type signatureKey: ECPublicKey\n        \"\"\"\n        self.senderKeyStates.append(SenderKeyState(id, iteration, chainKey, signatureKey))\n\n    def setSenderKeyState(self, id, iteration, chainKey, signatureKey):\n        \"\"\"\n        :type id: int\n        :type iteration: int\n        :type chainKey: bytearray\n        :type signatureKey: ECKeyPair\n        \"\"\"\n        del self.senderKeyStates[:]\n        self.senderKeyStates.append(SenderKeyState(id, iteration, chainKey, signatureKeyPair=signatureKey))\n\n    def serialize(self):\n        recordStructure = SenderKeyRecordStructure()\n\n        for senderKeyState in self.senderKeyStates:\n            recordStructure.senderKeyStates.extend([senderKeyState.getStructure()])\n\n        return recordStructure.SerializeToString()"
  },
  {
    "path": "axolotl/groups/state/senderkeystate.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ...state import storageprotos_pb2 as storageprotos\nfrom ..ratchet.senderchainkey import SenderChainKey\nfrom ..ratchet.sendermessagekey import SenderMessageKey\nfrom ...ecc.curve import Curve\n\n\nclass SenderKeyState:\n    def __init__(self, id=None, iteration=None, chainKey=None,\n                 signatureKeyPublic=None, signatureKeyPrivate=None,\n                 signatureKeyPair=None, senderKeyStateStructure=None):\n        \"\"\"\n        :type id: int\n        :type iteration: int\n        :type chainKey:  bytearray\n        :type signatureKeyPublic:  ECPublicKey\n        :type signatureKeyPrivate: ECPrivateKey\n        :type signatureKeyPair: ECKeyPair\n        :type senderKeyStateStructure: SenderKeyStateStructure\n        \"\"\"\n        assert (bool(id) and bool(iteration) and bool(chainKey)) or \\\n               (bool(senderKeyStateStructure) ^ bool(signatureKeyPublic or signatureKeyPair)) or \\\n               (bool(signatureKeyPublic) ^ bool(signatureKeyPair)), \"Missing required arguments\"\n\n        if senderKeyStateStructure:\n            self.senderKeyStateStructure = senderKeyStateStructure\n        else:\n            if signatureKeyPair:\n                signatureKeyPublic = signatureKeyPair.getPublicKey()\n                signatureKeyPrivate = signatureKeyPair.getPrivateKey()\n\n            self.senderKeyStateStructure = storageprotos.SenderKeyStateStructure()\n            senderChainKeyStructure = self.senderKeyStateStructure.SenderChainKey()\n            senderChainKeyStructure.iteration = iteration\n            senderChainKeyStructure.seed = chainKey\n            self.senderKeyStateStructure.senderChainKey.MergeFrom(senderChainKeyStructure)\n\n            signingKeyStructure = self.senderKeyStateStructure.SenderSigningKey()\n            signingKeyStructure.public = signatureKeyPublic.serialize()\n\n            if signatureKeyPrivate:\n                signingKeyStructure.private = signatureKeyPrivate.serialize()\n\n            self.senderKeyStateStructure.senderKeyId = id\n            self.senderChainKey = senderChainKeyStructure\n            self.senderKeyStateStructure.senderSigningKey.CopyFrom(signingKeyStructure)\n\n    def getKeyId(self):\n        return self.senderKeyStateStructure.senderKeyId\n\n    def getSenderChainKey(self):\n        return SenderChainKey(self.senderKeyStateStructure.senderChainKey.iteration,\n                              bytearray(self.senderKeyStateStructure.senderChainKey.seed))\n\n    def setSenderChainKey(self, chainKey):\n        self.senderKeyStateStructure.senderChainKey.iteration = chainKey.getIteration()\n        self.senderKeyStateStructure.senderChainKey.seed = chainKey.getSeed()\n\n    def getSigningKeyPublic(self):\n        return Curve.decodePoint(bytearray(self.senderKeyStateStructure.senderSigningKey.public), 0)\n\n    def getSigningKeyPrivate(self):\n        return Curve.decodePrivatePoint(self.senderKeyStateStructure.senderSigningKey.private)\n\n    def hasSenderMessageKey(self, iteration):\n        for senderMessageKey in self.senderKeyStateStructure.senderMessageKeys:\n            if senderMessageKey.iteration == iteration:\n                return True\n\n        return False\n\n    def addSenderMessageKey(self, senderMessageKey):\n        smk = self.senderKeyStateStructure.SenderMessageKey()\n        smk.iteration = senderMessageKey.iteration\n        smk.seed = senderMessageKey.seed\n        self.senderKeyStateStructure.senderMessageKeys.extend([smk])\n\n    def removeSenderMessageKey(self, iteration):\n        keys = self.senderKeyStateStructure.senderMessageKeys\n        result = None\n\n        for i in range(0, len(keys)):\n            senderMessageKey = keys[i]\n            if senderMessageKey.iteration == iteration:\n                result = senderMessageKey\n                del keys[i]\n                break\n\n        if result is not None:\n            return SenderMessageKey(result.iteration, bytearray(result.seed))\n\n        return None\n\n    def getStructure(self):\n        return self.senderKeyStateStructure\n"
  },
  {
    "path": "axolotl/groups/state/senderkeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass SenderKeyStore(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def storeSenderKey(self, senderKeyId, senderKeyRecord):\n        \"\"\"\n        :type senderKeyId: str\n        :type senderKeyRecord: SenderKeyRecord\n        \"\"\"\n\n    @abc.abstractmethod\n    def loadSenderKey(self, senderKeyId):\n        \"\"\"\n        :type senderKeyId: str\n        \"\"\"\n"
  },
  {
    "path": "axolotl/identitykey.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .ecc.curve import Curve\n\n\nclass IdentityKey:\n    def __init__(self, ecPubKeyOrBytes, offset=None):\n        if offset is None:\n            self.publicKey = ecPubKeyOrBytes\n        else:\n            self.publicKey = Curve.decodePoint(bytearray(ecPubKeyOrBytes), offset)\n\n    def getPublicKey(self):\n        return self.publicKey\n\n    def serialize(self):\n        return self.publicKey.serialize()\n\n    def get_fingerprint(self):\n        raise Exception(\"IMPL ME\")\n\n    def __eq__(self, other):\n        return self.publicKey == other.getPublicKey()\n\n    def hashCode(self):\n        raise Exception(\"IMPL ME\")\n"
  },
  {
    "path": "axolotl/identitykeypair.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .state.storageprotos_pb2 import IdentityKeyPairStructure\nfrom .identitykey import IdentityKey\nfrom .ecc.curve import Curve\n\n\nclass IdentityKeyPair:\n    def __init__(self, identityKeyPublicKey=None, ecPrivateKey=None, serialized=None):\n        if serialized:\n            structure = IdentityKeyPairStructure()\n            structure.ParseFromString(serialized)\n            self.publicKey = IdentityKey(bytearray(structure.publicKey), offset=0)\n            self.privateKey = Curve.decodePrivatePoint(bytearray(structure.privateKey))\n        else:\n            self.publicKey = identityKeyPublicKey\n            self.privateKey = ecPrivateKey\n\n    def getPublicKey(self):\n        return self.publicKey\n\n    def getPrivateKey(self):\n        return self.privateKey\n\n    def serialize(self):\n        structure = IdentityKeyPairStructure()\n        structure.publicKey = self.publicKey.serialize()\n        structure.privateKey = self.privateKey.serialize()\n        return structure.SerializeToString()\n"
  },
  {
    "path": "axolotl/invalidkeyexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass InvalidKeyException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/invalidkeyidexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass InvalidKeyIdException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/invalidmessageexception.py",
    "content": "# -*- cofing: utf-8 -*-\n\n\nclass InvalidMessageException(Exception):\n    def __init__(self, message, exceptions=None):\n        if exceptions:\n            message += str(exceptions[0])\n        super(InvalidMessageException, self).__init__(message)\n"
  },
  {
    "path": "axolotl/invalidversionexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass InvalidVersionException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/kdf/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n__author__ = 'tarek'\n"
  },
  {
    "path": "axolotl/kdf/derivedmessagesecrets.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..util.byteutil import ByteUtil\n\n\nclass DerivedMessageSecrets:\n    SIZE = 80\n    CIPHER_KEY_LENGTH = 32\n    MAC_KEY_LENGTH = 32\n    IV_LENGTH = 16\n\n    def __init__(self, okm):\n        keys = ByteUtil.split(okm,\n                              self.__class__.CIPHER_KEY_LENGTH,\n                              self.__class__.MAC_KEY_LENGTH,\n                              self.__class__.IV_LENGTH)\n        self.cipherKey = keys[0]  # AES\n        self.macKey = keys[1]  # sha256\n        self.iv = keys[2]\n\n    def getCipherKey(self):\n        return self.cipherKey\n\n    def getMacKey(self):\n        return self.macKey\n\n    def getIv(self):\n        return self.iv\n"
  },
  {
    "path": "axolotl/kdf/derivedrootsecrets.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..util.byteutil import ByteUtil\n\n\nclass DerivedRootSecrets:\n    SIZE = 64\n\n    def __init__(self, okm):\n        keys = ByteUtil.split(okm, 32, 32)\n        self.rootKey = keys[0]\n        self.chainKey = keys[1]\n\n    def getRootKey(self):\n        return self.rootKey\n\n    def getChainKey(self):\n        return self.chainKey\n"
  },
  {
    "path": "axolotl/kdf/hkdf.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\nimport hmac\nimport hashlib\nimport math\n\n\nclass HKDF(object):\n    __metaclass__ = abc.ABCMeta\n    HASH_OUTPUT_SIZE = 32\n\n    @staticmethod\n    def createFor(messageVersion):\n        from .hkdfv2 import HKDFv2\n        from .hkdfv3 import HKDFv3\n\n        if messageVersion == 2:\n            return HKDFv2()\n        elif messageVersion == 3:\n            return HKDFv3()\n        else:\n            raise AssertionError(\"Unknown version: %s \" % messageVersion)\n\n    def deriveSecrets(self, inputKeyMaterial, info, outputLength, salt=None):\n        salt = salt or bytearray(self.__class__.HASH_OUTPUT_SIZE)\n        prk = self.extract(salt, inputKeyMaterial)\n        return self.expand(prk, info, outputLength)\n\n    def extract(self, salt, inputKeyMaterial):\n        mac = hmac.new(bytes(salt), digestmod=hashlib.sha256)\n        mac.update(bytes(inputKeyMaterial))\n        return mac.digest()\n\n    def expand(self, prk, info, outputSize):\n        iterations = int(math.ceil(float(outputSize) / float(self.__class__.HASH_OUTPUT_SIZE)))\n        mixin = bytearray()\n        results = bytearray()\n        remainingBytes = outputSize\n\n        for i in range(self.getIterationStartOffset(), iterations + self.getIterationStartOffset()):\n            mac = hmac.new(prk, digestmod=hashlib.sha256)\n            mac.update(bytes(mixin))\n            if info is not None:\n                mac.update(bytes(info))\n            updateChr = chr(i % 256)\n            mac.update(updateChr.encode())\n\n            stepResult = mac.digest()\n            stepSize = min(remainingBytes, len(stepResult))\n            results.extend(stepResult[:stepSize])\n            mixin = stepResult\n            remainingBytes -= stepSize\n\n        return bytes(results)\n\n    @abc.abstractmethod\n    def getIterationStartOffset(self):\n        return 0\n"
  },
  {
    "path": "axolotl/kdf/hkdfv2.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .hkdf import HKDF\n\n\nclass HKDFv2(HKDF):\n    def getIterationStartOffset(self):\n        return 0\n"
  },
  {
    "path": "axolotl/kdf/hkdfv3.py",
    "content": "# -*- codsing: utf-8 -*-\n\nfrom .hkdf import HKDF\n\n\nclass HKDFv3(HKDF):\n    def getIterationStartOffset(self):\n        return 1\n"
  },
  {
    "path": "axolotl/kdf/messagekeys.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass MessageKeys:\n    def __init__(self, cipherKey, macKey, iv, counter):\n        self.cipherKey = cipherKey\n        self.macKey = macKey\n        self.iv = iv\n        self.counter = counter\n\n    def getCipherKey(self):\n        return self.cipherKey\n\n    def getMacKey(self):\n        return self.macKey\n\n    def getIv(self):\n        return self.iv\n\n    def getCounter(self):\n        return self.counter\n"
  },
  {
    "path": "axolotl/legacymessageexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass LegacyMessageException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/nosessionexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass NoSessionException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/protobuf/LocalStorageProtocol.proto",
    "content": "package textsecure;\n\noption java_package = \"org.whispersystems.libaxolotl.state\";\noption java_outer_classname = \"StorageProtos\";\n\nmessage SessionStructure {\n    message Chain {\n        optional bytes senderRatchetKey = 1;\n        optional bytes senderRatchetKeyPrivate = 2;\n\n        message ChainKey {\n            optional uint32 index = 1;\n            optional bytes  key   = 2;\n        }\n\n        optional ChainKey chainKey = 3;\n\n        message MessageKey {\n            optional uint32 index     = 1;\n            optional bytes  cipherKey = 2;\n            optional bytes  macKey    = 3;\n            optional bytes  iv        = 4;\n        }\n\n        repeated MessageKey messageKeys = 4;\n    }\n\n    message PendingKeyExchange {\n        optional uint32 sequence                 = 1;\n        optional bytes  localBaseKey             = 2;\n        optional bytes  localBaseKeyPrivate      = 3;\n        optional bytes  localRatchetKey          = 4;\n        optional bytes  localRatchetKeyPrivate   = 5;\n        optional bytes  localIdentityKey         = 7;\n        optional bytes  localIdentityKeyPrivate  = 8;\n    }\n\n    message PendingPreKey {\n        optional uint32 preKeyId       = 1;\n        optional int32  signedPreKeyId = 3;\n        optional bytes  baseKey        = 2;\n    }\n\n    optional uint32 sessionVersion      = 1;\n    optional bytes localIdentityPublic  = 2;\n    optional bytes remoteIdentityPublic = 3;\n\n    optional bytes rootKey              = 4;\n    optional uint32 previousCounter     = 5;\n\n    optional Chain senderChain          = 6;\n    repeated Chain receiverChains       = 7;\n\n    optional PendingKeyExchange pendingKeyExchange = 8;\n    optional PendingPreKey      pendingPreKey      = 9;\n\n    optional uint32 remoteRegistrationId = 10;\n    optional uint32 localRegistrationId  = 11;\n\n    optional bool needsRefresh = 12;\n    optional bytes aliceBaseKey = 13;\n}\n\nmessage RecordStructure {\n    optional SessionStructure currentSession   = 1;\n    repeated SessionStructure previousSessions = 2;\n}\n\nmessage PreKeyRecordStructure {\n    optional uint32 id        = 1;\n    optional bytes  publicKey = 2;\n    optional bytes  privateKey = 3;\n}\n\nmessage SignedPreKeyRecordStructure {\n    optional uint32  id         = 1;\n    optional bytes   publicKey  = 2;\n    optional bytes   privateKey = 3;\n    optional bytes   signature  = 4;\n    optional fixed64 timestamp  = 5;\n}\n\nmessage IdentityKeyPairStructure {\n    optional bytes publicKey  = 1;\n    optional bytes privateKey = 2;\n}\n\nmessage SenderKeyStateStructure {\n    message SenderChainKey {\n        optional uint32 iteration = 1;\n        optional bytes  seed      = 2;\n    }\n\n    message SenderMessageKey {\n        optional uint32 iteration = 1;\n        optional bytes  seed      = 2;\n    }\n\n    message SenderSigningKey {\n        optional bytes public  = 1;\n        optional bytes private = 2;\n    }\n\n    optional uint32           senderKeyId       = 1;\n    optional SenderChainKey   senderChainKey    = 2;\n    optional SenderSigningKey senderSigningKey  = 3;\n    repeated SenderMessageKey senderMessageKeys = 4;\n}\n\nmessage SenderKeyRecordStructure {\n    repeated SenderKeyStateStructure senderKeyStates = 1;\n}"
  },
  {
    "path": "axolotl/protobuf/WhisperTextProtocol.proto",
    "content": "package textsecure;\n\noption java_package = \"org.whispersystems.libaxolotl.protocol\";\noption java_outer_classname = \"WhisperProtos\";\n\nmessage WhisperMessage {\n  optional bytes  ratchetKey      = 1;\n  optional uint32 counter         = 2;\n  optional uint32 previousCounter = 3;\n  optional bytes  ciphertext      = 4;\n}\n\nmessage PreKeyWhisperMessage {\n  optional uint32 registrationId = 5;\n  optional uint32 preKeyId       = 1;\n  optional uint32 signedPreKeyId = 6;\n  optional bytes  baseKey        = 2;\n  optional bytes  identityKey    = 3;\n  optional bytes  message        = 4; // WhisperMessage\n}\n\nmessage KeyExchangeMessage {\n  optional uint32 id               = 1;\n  optional bytes  baseKey          = 2;\n  optional bytes  ratchetKey       = 3;\n  optional bytes  identityKey      = 4;\n  optional bytes  baseKeySignature = 5;\n}\n\nmessage SenderKeyMessage {\n  optional uint32 id         = 1;\n  optional uint32 iteration  = 2;\n  optional bytes  ciphertext = 3;\n}\n\nmessage SenderKeyDistributionMessage {\n  optional uint32 id         = 1;\n  optional uint32 iteration  = 2;\n  optional bytes  chainKey   = 3;\n  optional bytes  signingKey = 4;\n}"
  },
  {
    "path": "axolotl/protocol/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n__author__ = 'tarek'\n"
  },
  {
    "path": "axolotl/protocol/ciphertextmessage.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass CiphertextMessage(object):\n    __metaclass__ = abc.ABCMeta\n\n    UNSUPPORTED_VERSION = 1\n    CURRENT_VERSION = 3\n\n    WHISPER_TYPE = 2\n    PREKEY_TYPE = 3\n    SENDERKEY_TYPE = 4\n    SENDERKEY_DISTRIBUTION_TYPE = 5\n\n    # This should be the worst case (worse than V2). So not always accurate, but good enough for padding.\n    ENCRYPTED_MESSAGE_OVERHEAD = 53\n\n    @abc.abstractmethod\n    def serialize(self):\n        return\n\n    @abc.abstractmethod\n    def getType(self):\n        return\n"
  },
  {
    "path": "axolotl/protocol/keyexchangemessage.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .ciphertextmessage import CiphertextMessage\nfrom ..util.byteutil import ByteUtil\nfrom . import whisperprotos_pb2 as whisperprotos\nfrom ..legacymessageexception import LegacyMessageException\nfrom ..invalidversionexception import InvalidVersionException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..ecc.curve import Curve\nfrom ..identitykey import IdentityKey\n\n\nclass KeyExchangeMessage:\n    INITIATE_FLAG = 0x01\n    RESPONSE_FLAG = 0X02\n    SIMULTAENOUS_INITIATE_FLAG = 0x04\n\n    def __init__(self, messageVersion=None, sequence=None, flags=None, baseKey=None,\n                 baseKeySignature=None, ratchetKey=None, identityKey=None, serialized=None):\n        \"\"\"\n        :type messageVersion: int\n        :type  sequence: int\n        :type flags:int\n        :type baseKey: ECPublicKey\n        :type baseKeySignature: bytearray\n        :type ratchetKey: ECPublicKey\n        :type identityKey: IdentityKey\n        :type serialized: bytearray\n        \"\"\"\n        if serialized:\n            try:\n                parts = ByteUtil.split(serialized, 1, len(serialized) - 1)\n                self.version = ByteUtil.highBitsToInt(parts[0][0])\n                self.supportedVersion = ByteUtil.lowBitsToInt(parts[0][0])\n                if self.version < CiphertextMessage.CURRENT_VERSION:\n                    raise LegacyMessageException(\"Unsupportmessageed legacy version: %s\" % self.version)\n                if self.version > CiphertextMessage.CURRENT_VERSION:\n                    raise InvalidVersionException(\"Unkown version: %s\" % self.version)\n                message = whisperprotos.KeyExchangeMessage()\n                message.ParseFromString(bytes(parts[1]))\n\n                if (not message.HasField(\"id\") or not message.HasField(\"baseKey\") or\n                        not message.HasField(\"ratchetKey\") or not message.HasField(\"identityKey\") or\n                        not message.HasField(\"baseKeySignature\")):\n                    raise InvalidMessageException(\"Some required fields are missing!\")\n\n                self.sequence = message.id >> 5\n                self.flags = message.id & 0x1f\n                self.serialized = serialized\n                self.baseKey = Curve.decodePoint(bytearray(message.baseKey), 0)\n                self.baseKeySignature = message.baseKeySignature\n                self.ratchetKey = Curve.decodePoint(bytearray(message.ratchetKey), 0)\n                self.identityKey = IdentityKey(message.identityKey, 0)\n\n            except InvalidKeyException as e:\n                raise InvalidMessageException(e)\n        else:\n            self.supportedVersion = CiphertextMessage.CURRENT_VERSION\n            self.version = messageVersion\n            self.sequence = sequence\n            self.flags = flags\n            self.baseKey = baseKey\n            self.baseKeySignature = baseKeySignature\n            self.ratchetKey = ratchetKey\n            self.identityKey = identityKey\n\n            version = [ByteUtil.intsToByteHighAndLow(self.version, self.supportedVersion)]\n            keyExchangeMessage = whisperprotos.KeyExchangeMessage()\n            keyExchangeMessage.id = (self.sequence << 5) | self.flags\n            keyExchangeMessage.baseKey = baseKey.serialize()\n            keyExchangeMessage.ratchetKey = ratchetKey.serialize()\n            keyExchangeMessage.identityKey = identityKey.serialize()\n\n            if messageVersion >= 3:\n                keyExchangeMessage.baseKeySignature = baseKeySignature\n\n            self.serialized = ByteUtil.combine(version, keyExchangeMessage.SerializeToString())\n\n    def getVersion(self):\n        return self.version\n\n    def getBaseKey(self):\n        return self.baseKey\n\n    def getBaseKeySignature(self):\n        return self.baseKeySignature\n\n    def getRatchetKey(self):\n        return self.ratchetKey\n\n    def getIdentityKey(self):\n        return self.identityKey\n\n    def hasIdentityKey(self):\n        return True\n\n    def getMaxVersion(self):\n        return self.supportedVersion\n\n    def isResponse(self):\n        return ((self.flags & self.__class__.RESPONSE_FLAG) != 0)\n\n    def isInitiate(self):\n        return (self.flags & self.__class__.INITIATE_FLAG) != 0\n\n    def isResponseForSimultaneousInitiate(self):\n        return (self.flags & self.__class__.SIMULTAENOUS_INITIATE_FLAG) != 0\n\n    def getFlags(self):\n        return self.flags\n\n    def getSequence(self):\n        return self.sequence\n\n    def serialize(self):\n        return self.serialized\n"
  },
  {
    "path": "axolotl/protocol/prekeywhispermessage.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom google.protobuf.message import DecodeError\n\nfrom .ciphertextmessage import CiphertextMessage\nfrom ..util.byteutil import ByteUtil\nfrom ..ecc.curve import Curve\nfrom ..identitykey import IdentityKey\nfrom .whispermessage import WhisperMessage\nfrom ..invalidversionexception import InvalidVersionException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..legacymessageexception import LegacyMessageException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom . import whisperprotos_pb2 as whisperprotos\n\n\nclass PreKeyWhisperMessage(CiphertextMessage):\n    def __init__(self, messageVersion=None, registrationId=None, preKeyId=None,\n                 signedPreKeyId=None, ecPublicBaseKey=None, identityKey=None,\n                 whisperMessage=None, serialized=None):\n        if serialized:\n            try:\n                self.version = ByteUtil.highBitsToInt(serialized[0])\n                if self.version > CiphertextMessage.CURRENT_VERSION:\n                    raise InvalidVersionException(\"Unknown version %s\" % self.version)\n\n                if self.version < CiphertextMessage.CURRENT_VERSION:\n                    raise LegacyMessageException(\"Legacy version: %s\" % self.version)\n\n                preKeyWhisperMessage = whisperprotos.PreKeyWhisperMessage()\n                preKeyWhisperMessage.ParseFromString(serialized[1:])\n\n                if preKeyWhisperMessage.signedPreKeyId is None or \\\n                        not preKeyWhisperMessage.baseKey or \\\n                        not preKeyWhisperMessage.identityKey or \\\n                        not preKeyWhisperMessage.message:\n                    raise InvalidMessageException(\"Incomplete message\")\n\n                self.serialized = serialized\n                self.registrationId = preKeyWhisperMessage.registrationId\n                self.preKeyId = preKeyWhisperMessage.preKeyId\n                if preKeyWhisperMessage.signedPreKeyId is not None:\n                    self.signedPreKeyId = preKeyWhisperMessage.signedPreKeyId\n                else:\n                    self.signedPreKeyId = -1\n\n                self.baseKey = Curve.decodePoint(bytearray(preKeyWhisperMessage.baseKey), 0)\n\n                self.identityKey = IdentityKey(Curve.decodePoint(bytearray(preKeyWhisperMessage.identityKey), 0))\n                self.message = WhisperMessage(serialized=preKeyWhisperMessage.message)\n            except (InvalidKeyException, LegacyMessageException, DecodeError) as e:\n                raise InvalidMessageException(e)\n\n        else:\n            self.version = messageVersion\n            self.registrationId = registrationId\n            self.preKeyId = preKeyId\n            self.signedPreKeyId = signedPreKeyId\n            self.baseKey = ecPublicBaseKey\n            self.identityKey = identityKey\n            self.message = whisperMessage\n\n            builder = whisperprotos.PreKeyWhisperMessage()\n            builder.signedPreKeyId = signedPreKeyId\n            builder.baseKey = ecPublicBaseKey.serialize()\n            builder.identityKey = identityKey.serialize()\n            builder.message = whisperMessage.serialize()\n            builder.registrationId = registrationId\n\n            if preKeyId is not None:\n                builder.preKeyId = preKeyId\n\n            versionBytes = ByteUtil.intsToByteHighAndLow(self.version, self.__class__.CURRENT_VERSION)\n            messageBytes = builder.SerializeToString()\n            self.serialized = bytes(ByteUtil.combine(versionBytes, messageBytes))\n\n    def getMessageVersion(self):\n        return self.version\n\n    def getIdentityKey(self):\n        return self.identityKey\n\n    def getRegistrationId(self):\n        return self.registrationId\n\n    def getPreKeyId(self):\n        return self.preKeyId\n\n    def getSignedPreKeyId(self):\n        return self.signedPreKeyId\n\n    def getBaseKey(self):\n        return self.baseKey\n\n    def getWhisperMessage(self):\n        return self.message\n\n    def serialize(self):\n        return self.serialized\n\n    def getType(self):\n        return CiphertextMessage.PREKEY_TYPE\n"
  },
  {
    "path": "axolotl/protocol/senderkeydistributionmessage.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .ciphertextmessage import CiphertextMessage\nfrom . import whisperprotos_pb2 as whisperprotos\nfrom ..util.byteutil import ByteUtil\nfrom ..legacymessageexception import LegacyMessageException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..ecc.curve import Curve\nclass SenderKeyDistributionMessage(CiphertextMessage):\n    def __init__(self, id=None, iteration=None, chainKey=None, signatureKey=None, serialized=None):\n        \"\"\"\n        :type id: int\n        :type iteration: int\n        :type chainKey: bytearray\n        :type signatureKey: ECPublicKey\n        \"\"\"\n\n\n        assert bool(id is not None and iteration is not None and chainKey is not None and signatureKey is not None)\\\n               ^ bool(serialized),\\\n            \"Either pass arguments or serialized data\"\n\n        if serialized:\n            try:\n                messageParts = ByteUtil.split(serialized, 1, len(serialized)- 1)\n                version = messageParts[0][0]\n                message = messageParts[1]\n\n\n                if ByteUtil.highBitsToInt(version) < 3:\n                    raise LegacyMessageException(\"Legacy message: %s\" % ByteUtil.highBitsToInt(version))\n\n                if ByteUtil.highBitsToInt(version) > self.__class__.CURRENT_VERSION:\n                    raise InvalidMessageException(\"Unknown version: %s\" % ByteUtil.highBitsToInt(version))\n\n\n                distributionMessage = whisperprotos.SenderKeyDistributionMessage()\n                distributionMessage.ParseFromString(message)\n\n                if distributionMessage.id is None or distributionMessage.iteration is None\\\n                    or distributionMessage.chainKey is None or distributionMessage.signingKey is None:\n                    raise InvalidMessageException(\"Incomplete message\")\n\n                self.serialized = serialized\n\n                self.id           = distributionMessage.id\n                self.iteration    = distributionMessage.iteration\n                self.chainKey     = distributionMessage.chainKey\n                self.signatureKey = Curve.decodePoint(bytearray(distributionMessage.signingKey), 0)\n\n            except Exception as e:\n                raise InvalidMessageException(e)\n        else:\n            version = [ByteUtil.intsToByteHighAndLow(self.__class__.CURRENT_VERSION, self.__class__.CURRENT_VERSION)]\n            self.id = id\n            self.iteration = iteration\n            self.chainKey = chainKey\n            self.signatureKey = signatureKey\n            message = whisperprotos.SenderKeyDistributionMessage()\n            message.id = id\n            message.iteration = iteration\n            message.chainKey= bytes(chainKey)\n            message.signingKey = signatureKey.serialize()\n            message = message.SerializeToString()\n            self.serialized = bytes(ByteUtil.combine(version, message))\n\n    def serialize(self):\n        return self.serialized\n\n    def getType(self):\n        return self.__class__.SENDERKEY_DISTRIBUTION_TYPE\n\n    def getIteration(self):\n        return self.iteration\n\n    def getChainKey(self):\n        return self.chainKey\n\n    def getSignatureKey(self):\n        return self.signatureKey\n\n    def getId(self):\n        return self.id"
  },
  {
    "path": "axolotl/protocol/senderkeymessage.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .ciphertextmessage import CiphertextMessage\nfrom ..util.byteutil import ByteUtil\nfrom ..legacymessageexception import LegacyMessageException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..ecc.curve import Curve\nfrom . import whisperprotos_pb2 as whisperprotos\n\n\nclass SenderKeyMessage(CiphertextMessage):\n    SIGNATURE_LENGTH = 64\n\n    def __init__(self, keyId=None, iteration=None, ciphertext=None, signatureKey=None, serialized=None):\n        assert bool(keyId is not None and iteration is not None and ciphertext is not None and\n                    signatureKey is not None) ^ bool(serialized), \"Either pass arguments or serialized data\"\n\n        if serialized:\n            try:\n                messageParts = ByteUtil.split(serialized, 1, len(serialized) - 1 - self.__class__.SIGNATURE_LENGTH,\n                                              self.__class__.SIGNATURE_LENGTH)\n\n                version = messageParts[0][0]\n                message = messageParts[1]\n                signature = messageParts[2]\n\n                if ByteUtil.highBitsToInt(version) < 3:\n                    raise LegacyMessageException(\"Legacy message: %s\" % ByteUtil.highBitsToInt(version))\n\n                if ByteUtil.highBitsToInt(version) > self.__class__.CURRENT_VERSION:\n                    raise InvalidMessageException(\"Unknown version: %s\" % ByteUtil.highBitsToInt(version))\n\n                senderKeyMessage = whisperprotos.SenderKeyMessage()\n                senderKeyMessage.ParseFromString(message)\n\n                if senderKeyMessage.id is None or senderKeyMessage.iteration is None or \\\n                        senderKeyMessage.ciphertext is None:\n                    raise InvalidMessageException(\"Incomplete message\")\n\n                self.serialized = serialized\n                self.messageVersion = ByteUtil.highBitsToInt(version)\n\n                self.keyId = senderKeyMessage.id\n                self.iteration = senderKeyMessage.iteration\n                self.ciphertext = senderKeyMessage.ciphertext\n            except Exception as e:\n                raise InvalidMessageException(e)\n        else:\n            version = [ByteUtil.intsToByteHighAndLow(self.__class__.CURRENT_VERSION, self.__class__.CURRENT_VERSION)]\n\n            message = whisperprotos.SenderKeyMessage()\n            message.id = keyId\n            message.iteration = iteration\n            message.ciphertext = ciphertext\n            message = message.SerializeToString()\n\n            signature = self.getSignature(signatureKey, bytes(ByteUtil.combine(version, message)))\n\n            self.serialized = bytes(ByteUtil.combine(version, message, signature))\n            self.messageVersion = self.__class__.CURRENT_VERSION\n            self.keyId = keyId\n            self.iteration = iteration\n            self.ciphertext = ciphertext\n\n\n    def getKeyId(self):\n        return self.keyId\n\n    def getIteration(self):\n        return self.iteration\n\n    def getCipherText(self):\n        return self.ciphertext\n\n    def verifySignature(self, signatureKey):\n        \"\"\"\n        :type signatureKey: ECPublicKey\n        \"\"\"\n        try:\n            parts = ByteUtil.split(self.serialized,\n                                   len(self.serialized) - self.__class__.SIGNATURE_LENGTH,\n                                   self.__class__.SIGNATURE_LENGTH)\n\n            if not Curve.verifySignature(signatureKey, parts[0], parts[1]):\n                raise InvalidMessageException(\"Invalid signature!\")\n        except InvalidKeyException as e:\n            raise InvalidMessageException(e)\n\n    def getSignature(self, signatureKey, serialized):\n        \"\"\"\n        :type signatureKey: ECPrivateKey\n        :type serialized: bytearray\n        \"\"\"\n        try:\n            return Curve.calculateSignature(signatureKey, serialized)\n        except InvalidKeyException as e:\n            raise AssertionError(e)\n\n    def serialize(self):\n        return self.serialized\n\n    def getType(self):\n        return CiphertextMessage.SENDERKEY_TYPE"
  },
  {
    "path": "axolotl/protocol/whispermessage.py",
    "content": "# -*- cosing: utf-8 -*-\n\nimport hmac\nimport hashlib\n\nfrom .ciphertextmessage import CiphertextMessage\nfrom ..util.byteutil import ByteUtil\nfrom ..ecc.curve import Curve\nfrom . import whisperprotos_pb2 as whisperprotos\nfrom ..legacymessageexception import LegacyMessageException\nfrom ..invalidmessageexception import InvalidMessageException\nfrom ..invalidkeyexception import InvalidKeyException\n\n\nclass WhisperMessage(CiphertextMessage):\n    MAC_LENGTH = 8\n\n    def __init__(self, messageVersion=None, macKey=None, ECPublicKey_senderRatchetKey=None,\n                 counter=None, previousCounter=None, ciphertext=None, senderIdentityKey=None,\n                 receiverIdentityKey=None, serialized=None):\n        self.serialized = \"\"\n        if serialized:\n            try:\n                assert type(serialized) in (str, bytes), \"Expected serialized %s, got %s\" % (str, type(serialized))\n                messageParts = ByteUtil.split(serialized, 1, len(serialized) - 1 - WhisperMessage.MAC_LENGTH,\n                                              WhisperMessage.MAC_LENGTH)\n                version = messageParts[0][0]\n                message = messageParts[1]\n                mac = messageParts[2]\n\n                if ByteUtil.highBitsToInt(version) <= self.__class__.UNSUPPORTED_VERSION:\n                    raise LegacyMessageException(\"Legacy message %s\" % ByteUtil.highBitsToInt(version))\n\n                if ByteUtil.highBitsToInt(version) > self.__class__.CURRENT_VERSION:\n                    raise InvalidMessageException(\"Unknown version: %s\" % ByteUtil.highBitsToInt(version))\n\n                whisperMessage = whisperprotos.WhisperMessage()\n                whisperMessage.ParseFromString(message)\n\n                if not whisperMessage.ciphertext or whisperMessage.counter is None or not whisperMessage.ratchetKey:\n                    raise InvalidMessageException(\"Incomplete message\")\n\n                self.serialized = serialized\n                self.senderRatchetKey = Curve.decodePoint(bytearray(whisperMessage.ratchetKey), 0)\n                self.messageVersion = ByteUtil.highBitsToInt(version)\n                self.counter = whisperMessage.counter\n                self.previousCounter = whisperMessage.previousCounter\n                self.ciphertext = whisperMessage.ciphertext\n            except InvalidKeyException as e:\n                raise InvalidMessageException(e)\n        else:\n            version = ByteUtil.intsToByteHighAndLow(messageVersion, self.__class__.CURRENT_VERSION)\n            message = whisperprotos.WhisperMessage()\n            message.ratchetKey = ECPublicKey_senderRatchetKey.serialize()\n            message.counter = counter\n            message.previousCounter = previousCounter\n            message.ciphertext = ciphertext\n            message = message.SerializeToString()\n            mac = self.getMac(messageVersion, senderIdentityKey, receiverIdentityKey, macKey,\n                              ByteUtil.combine(version, message))\n            self.serialized = bytes(ByteUtil.combine(version, message, mac))\n            self.senderRatchetKey = ECPublicKey_senderRatchetKey\n            self.counter = counter\n            self.previousCounter = previousCounter\n            self.ciphertext = ciphertext\n            self.messageVersion = messageVersion\n\n    def getSenderRatchetKey(self):\n        return self.senderRatchetKey\n\n    def getMessageVersion(self):\n        return self.messageVersion\n\n    def getCounter(self):\n        return self.counter\n\n    def getBody(self):\n        return self.ciphertext\n\n    def verifyMac(self, messageVersion, senderIdentityKey, receiverIdentityKey, macKey):\n        parts = ByteUtil.split(self.serialized,\n                               len(self.serialized) - self.__class__.MAC_LENGTH,\n                               self.__class__.MAC_LENGTH)\n        ourMac = self.getMac(messageVersion, senderIdentityKey, receiverIdentityKey, macKey, parts[0])\n        theirMac = parts[1]\n\n        if ourMac != theirMac:\n            raise InvalidMessageException(\"Bad Mac!\")\n\n    def getMac(self, messageVersion, senderIdentityKey, receiverIdentityKey, macKey, serialized):\n        mac = hmac.new(macKey, digestmod=hashlib.sha256)\n        if messageVersion >= 3:\n            mac.update(senderIdentityKey.getPublicKey().serialize())\n            mac.update(receiverIdentityKey.getPublicKey().serialize())\n\n        mac.update(bytes(serialized))\n        fullMac = mac.digest()\n        return ByteUtil.trim(fullMac, self.__class__.MAC_LENGTH)\n\n    def serialize(self):\n        return self.serialized\n\n    def getType(self):\n        return CiphertextMessage.WHISPER_TYPE\n\n    def isLegacy(self, message):\n        return message is not None and \\\n                len(message) >= 1 and \\\n                ByteUtil.highBitsToInt(message[0]) <= CiphertextMessage.UNSUPPORTED_VERSION\n"
  },
  {
    "path": "axolotl/protocol/whisperprotos_pb2.py",
    "content": "# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: WhisperTextProtocol.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import reflection as _reflection\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf import descriptor_pb2\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor.FileDescriptor(\n  name='WhisperTextProtocol.proto',\n  package='textsecure',\n  serialized_pb=_b('\\n\\x19WhisperTextProtocol.proto\\x12\\ntextsecure\\\"b\\n\\x0eWhisperMessage\\x12\\x12\\n\\nratchetKey\\x18\\x01 \\x01(\\x0c\\x12\\x0f\\n\\x07\\x63ounter\\x18\\x02 \\x01(\\r\\x12\\x17\\n\\x0fpreviousCounter\\x18\\x03 \\x01(\\r\\x12\\x12\\n\\nciphertext\\x18\\x04 \\x01(\\x0c\\\"\\x8f\\x01\\n\\x14PreKeyWhisperMessage\\x12\\x16\\n\\x0eregistrationId\\x18\\x05 \\x01(\\r\\x12\\x10\\n\\x08preKeyId\\x18\\x01 \\x01(\\r\\x12\\x16\\n\\x0esignedPreKeyId\\x18\\x06 \\x01(\\r\\x12\\x0f\\n\\x07\\x62\\x61seKey\\x18\\x02 \\x01(\\x0c\\x12\\x13\\n\\x0bidentityKey\\x18\\x03 \\x01(\\x0c\\x12\\x0f\\n\\x07message\\x18\\x04 \\x01(\\x0c\\\"t\\n\\x12KeyExchangeMessage\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\r\\x12\\x0f\\n\\x07\\x62\\x61seKey\\x18\\x02 \\x01(\\x0c\\x12\\x12\\n\\nratchetKey\\x18\\x03 \\x01(\\x0c\\x12\\x13\\n\\x0bidentityKey\\x18\\x04 \\x01(\\x0c\\x12\\x18\\n\\x10\\x62\\x61seKeySignature\\x18\\x05 \\x01(\\x0c\\\"E\\n\\x10SenderKeyMessage\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\r\\x12\\x11\\n\\titeration\\x18\\x02 \\x01(\\r\\x12\\x12\\n\\nciphertext\\x18\\x03 \\x01(\\x0c\\\"c\\n\\x1cSenderKeyDistributionMessage\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\r\\x12\\x11\\n\\titeration\\x18\\x02 \\x01(\\r\\x12\\x10\\n\\x08\\x63hainKey\\x18\\x03 \\x01(\\x0c\\x12\\x12\\n\\nsigningKey\\x18\\x04 \\x01(\\x0c\\x42\\x37\\n&org.whispersystems.libaxolotl.protocolB\\rWhisperProtos')\n)\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n\n\n\n\n_WHISPERMESSAGE = _descriptor.Descriptor(\n  name='WhisperMessage',\n  full_name='textsecure.WhisperMessage',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='ratchetKey', full_name='textsecure.WhisperMessage.ratchetKey', index=0,\n      number=1, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='counter', full_name='textsecure.WhisperMessage.counter', index=1,\n      number=2, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='previousCounter', full_name='textsecure.WhisperMessage.previousCounter', index=2,\n      number=3, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='ciphertext', full_name='textsecure.WhisperMessage.ciphertext', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=41,\n  serialized_end=139,\n)\n\n\n_PREKEYWHISPERMESSAGE = _descriptor.Descriptor(\n  name='PreKeyWhisperMessage',\n  full_name='textsecure.PreKeyWhisperMessage',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='registrationId', full_name='textsecure.PreKeyWhisperMessage.registrationId', index=0,\n      number=5, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='preKeyId', full_name='textsecure.PreKeyWhisperMessage.preKeyId', index=1,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='signedPreKeyId', full_name='textsecure.PreKeyWhisperMessage.signedPreKeyId', index=2,\n      number=6, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='baseKey', full_name='textsecure.PreKeyWhisperMessage.baseKey', index=3,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='identityKey', full_name='textsecure.PreKeyWhisperMessage.identityKey', index=4,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='message', full_name='textsecure.PreKeyWhisperMessage.message', index=5,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=142,\n  serialized_end=285,\n)\n\n\n_KEYEXCHANGEMESSAGE = _descriptor.Descriptor(\n  name='KeyExchangeMessage',\n  full_name='textsecure.KeyExchangeMessage',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='textsecure.KeyExchangeMessage.id', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='baseKey', full_name='textsecure.KeyExchangeMessage.baseKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='ratchetKey', full_name='textsecure.KeyExchangeMessage.ratchetKey', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='identityKey', full_name='textsecure.KeyExchangeMessage.identityKey', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='baseKeySignature', full_name='textsecure.KeyExchangeMessage.baseKeySignature', index=4,\n      number=5, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=287,\n  serialized_end=403,\n)\n\n\n_SENDERKEYMESSAGE = _descriptor.Descriptor(\n  name='SenderKeyMessage',\n  full_name='textsecure.SenderKeyMessage',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='textsecure.SenderKeyMessage.id', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='iteration', full_name='textsecure.SenderKeyMessage.iteration', index=1,\n      number=2, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='ciphertext', full_name='textsecure.SenderKeyMessage.ciphertext', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=405,\n  serialized_end=474,\n)\n\n\n_SENDERKEYDISTRIBUTIONMESSAGE = _descriptor.Descriptor(\n  name='SenderKeyDistributionMessage',\n  full_name='textsecure.SenderKeyDistributionMessage',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='textsecure.SenderKeyDistributionMessage.id', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='iteration', full_name='textsecure.SenderKeyDistributionMessage.iteration', index=1,\n      number=2, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='chainKey', full_name='textsecure.SenderKeyDistributionMessage.chainKey', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='signingKey', full_name='textsecure.SenderKeyDistributionMessage.signingKey', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=476,\n  serialized_end=575,\n)\n\nDESCRIPTOR.message_types_by_name['WhisperMessage'] = _WHISPERMESSAGE\nDESCRIPTOR.message_types_by_name['PreKeyWhisperMessage'] = _PREKEYWHISPERMESSAGE\nDESCRIPTOR.message_types_by_name['KeyExchangeMessage'] = _KEYEXCHANGEMESSAGE\nDESCRIPTOR.message_types_by_name['SenderKeyMessage'] = _SENDERKEYMESSAGE\nDESCRIPTOR.message_types_by_name['SenderKeyDistributionMessage'] = _SENDERKEYDISTRIBUTIONMESSAGE\n\nWhisperMessage = _reflection.GeneratedProtocolMessageType('WhisperMessage', (_message.Message,), dict(\n  DESCRIPTOR = _WHISPERMESSAGE,\n  __module__ = 'WhisperTextProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.WhisperMessage)\n  ))\n_sym_db.RegisterMessage(WhisperMessage)\n\nPreKeyWhisperMessage = _reflection.GeneratedProtocolMessageType('PreKeyWhisperMessage', (_message.Message,), dict(\n  DESCRIPTOR = _PREKEYWHISPERMESSAGE,\n  __module__ = 'WhisperTextProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.PreKeyWhisperMessage)\n  ))\n_sym_db.RegisterMessage(PreKeyWhisperMessage)\n\nKeyExchangeMessage = _reflection.GeneratedProtocolMessageType('KeyExchangeMessage', (_message.Message,), dict(\n  DESCRIPTOR = _KEYEXCHANGEMESSAGE,\n  __module__ = 'WhisperTextProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.KeyExchangeMessage)\n  ))\n_sym_db.RegisterMessage(KeyExchangeMessage)\n\nSenderKeyMessage = _reflection.GeneratedProtocolMessageType('SenderKeyMessage', (_message.Message,), dict(\n  DESCRIPTOR = _SENDERKEYMESSAGE,\n  __module__ = 'WhisperTextProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SenderKeyMessage)\n  ))\n_sym_db.RegisterMessage(SenderKeyMessage)\n\nSenderKeyDistributionMessage = _reflection.GeneratedProtocolMessageType('SenderKeyDistributionMessage', (_message.Message,), dict(\n  DESCRIPTOR = _SENDERKEYDISTRIBUTIONMESSAGE,\n  __module__ = 'WhisperTextProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SenderKeyDistributionMessage)\n  ))\n_sym_db.RegisterMessage(SenderKeyDistributionMessage)\n\n\nDESCRIPTOR.has_options = True\nDESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\\n&org.whispersystems.libaxolotl.protocolB\\rWhisperProtos'))\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "axolotl/ratchet/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/ratchet/aliceaxolotlparameters.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass AliceAxolotlParameters:\n    def __init__(self, ourIdentityKey, ourBaseKey, theirIdentityKey, theirSignedPreKey,\n                 theirRatchetKey, theirOneTimePreKey):\n        \"\"\"\n        :type ourBaseKey: ECKeyPair\n        :type theirSignedPreKey: ECKeyPair\n        :type ourIdentityKey: IdentityKeyPair\n        :type theirOneTimePreKey: ECPublicKey\n        :type theirRatchetKey: ECKeyPair\n        :type theirIdentityKey: IdentityKey\n        \"\"\"\n        self.ourBaseKey = ourBaseKey\n        self.ourIdentityKey = ourIdentityKey\n        self.theirSignedPreKey = theirSignedPreKey\n        self.theirRatchetKey = theirRatchetKey\n        self.theirIdentityKey = theirIdentityKey\n        self.theirOneTimePreKey = theirOneTimePreKey\n\n        if ourBaseKey is None or ourIdentityKey is None or theirSignedPreKey is None \\\n                or theirRatchetKey is None or theirIdentityKey is None or theirSignedPreKey is None:\n            raise ValueError(\"Null value!\")\n\n    def getOurIdentityKey(self):\n        return self.ourIdentityKey\n\n    def getOurBaseKey(self):\n        return self.ourBaseKey\n\n    def getTheirIdentityKey(self):\n        return self.theirIdentityKey\n\n    def getTheirSignedPreKey(self):\n        return self.theirSignedPreKey\n\n    def getTheirOneTimePreKey(self):\n        return self.theirOneTimePreKey\n\n    def getTheirRatchetKey(self):\n        return self.theirRatchetKey\n\n    @staticmethod\n    def newBuilder():\n        return AliceAxolotlParameters.Builder()\n\n    class Builder:\n        def __init__(self):\n            self.ourIdentityKey = None\n            self.ourBaseKey = None\n            self.theirIdentityKey = None\n            self.theirSignedPreKey = None\n            self.theirRatchetKey = None\n            self.theirOneTimePreKey = None\n\n        def setOurIdentityKey(self, ourIdentityKey):\n            self.ourIdentityKey = ourIdentityKey\n            return self\n\n        def setOurBaseKey(self, ourBaseKey):\n            self.ourBaseKey = ourBaseKey\n            return self\n\n        def setTheirRatchetKey(self, theirRatchetKey):\n            self.theirRatchetKey = theirRatchetKey\n            return self\n\n        def setTheirIdentityKey(self, theirIdentityKey):\n            self.theirIdentityKey = theirIdentityKey\n            return self\n\n        def setTheirSignedPreKey(self, theirSignedPreKey):\n            self.theirSignedPreKey = theirSignedPreKey\n            return self\n\n        def setTheirOneTimePreKey(self, theirOneTimePreKey):\n            self.theirOneTimePreKey = theirOneTimePreKey\n            return self\n\n        def create(self):\n            return AliceAxolotlParameters(self.ourIdentityKey, self.ourBaseKey, self.theirIdentityKey,\n                                          self.theirSignedPreKey, self.theirRatchetKey, self.theirOneTimePreKey)\n"
  },
  {
    "path": "axolotl/ratchet/bobaxolotlparamaters.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass BobAxolotlParameters:\n    def __init__(self, ourIdentityKey, ourSignedPreKey, ourRatchetKey, ourOneTimePreKey,\n                 theirIdentityKey, theirBaseKey):\n        \"\"\"\n        :type ourIdentityKey: IdentityKeyPair\n        :type ourSignedPreKey: ECKeyPair\n        :type ourRatchetKey: ECKeyPair\n        :type ourOneTimePreKey: ECKeyPair\n        :type theirIdentityKey: IdentityKey\n        :type theirBaseKey: ECPublicKey\n        \"\"\"\n        self.ourIdentityKey = ourIdentityKey\n        self.ourSignedPreKey = ourSignedPreKey\n        self.ourRatchetKey = ourRatchetKey\n        self.ourOneTimePreKey = ourOneTimePreKey\n        self.theirIdentityKey = theirIdentityKey\n        self.theirBaseKey = theirBaseKey\n\n        if ourIdentityKey is None or ourSignedPreKey is None or ourRatchetKey is None \\\n                or theirIdentityKey is None or theirBaseKey is None:\n            raise ValueError(\"Null value!\")\n\n    def getOurIdentityKey(self):\n        return self.ourIdentityKey\n\n    def getOurSignedPreKey(self):\n        return self.ourSignedPreKey\n\n    def getOurOneTimePreKey(self):\n        return self.ourOneTimePreKey\n\n    def getTheirIdentityKey(self):\n        return self.theirIdentityKey\n\n    def getTheirBaseKey(self):\n        return self.theirBaseKey\n\n    def getOurRatchetKey(self):\n        return self.ourRatchetKey\n\n    @staticmethod\n    def newBuilder():\n        return BobAxolotlParameters.Builder()\n\n    class Builder:\n        def __init__(self):\n            self.ourIdentityKey = None\n            self.ourSignedPreKey = None\n            self.ourOneTimePreKey = None\n            self.ourRatchetKey = None\n            self.theirIdentityKey = None\n            self.theirBaseKey = None\n\n        def setOurIdentityKey(self, ourIdentityKey):\n            self.ourIdentityKey = ourIdentityKey\n            return self\n\n        def setOurSignedPreKey(self, ourSignedPreKey):\n            self.ourSignedPreKey = ourSignedPreKey\n            return self\n\n        def setOurOneTimePreKey(self, ourOneTimePreKey):\n            self.ourOneTimePreKey = ourOneTimePreKey\n            return self\n\n        def setOurRatchetKey(self, ourRatchetKey):\n            self.ourRatchetKey = ourRatchetKey\n            return self\n\n        def setTheirIdentityKey(self, theirIdentityKey):\n            self.theirIdentityKey = theirIdentityKey\n            return self\n\n        def setTheirBaseKey(self, theirBaseKey):\n            self.theirBaseKey = theirBaseKey\n            return self\n\n        def create(self):\n            return BobAxolotlParameters(self.ourIdentityKey, self.ourSignedPreKey, self.ourRatchetKey,\n                                        self.ourOneTimePreKey, self.theirIdentityKey, self.theirBaseKey)\n"
  },
  {
    "path": "axolotl/ratchet/chainkey.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport hmac\nimport hashlib\n\nfrom ..kdf.derivedmessagesecrets import DerivedMessageSecrets\nfrom ..kdf.messagekeys import MessageKeys\n\n\nclass ChainKey:\n    MESSAGE_KEY_SEED = bytearray([0x01])\n    CHAIN_KEY_SEED = bytearray([0x02])\n\n    def __init__(self, kdf, key, index):\n        self.kdf = kdf\n        self.key = key\n        self.index = index\n\n    def getKey(self):\n        return self.key\n\n    def getIndex(self):\n        return self.index\n\n    def getNextChainKey(self):\n        nextKey = self.getBaseMaterial(self.__class__.CHAIN_KEY_SEED)\n        return ChainKey(self.kdf, nextKey, self.index + 1)\n\n    def getMessageKeys(self):\n        inputKeyMaterial = self.getBaseMaterial(self.__class__.MESSAGE_KEY_SEED)\n        keyMaterialBytes = self.kdf.deriveSecrets(inputKeyMaterial,\n                                                  bytearray(\"WhisperMessageKeys\".encode()),\n                                                  DerivedMessageSecrets.SIZE)\n        keyMaterial = DerivedMessageSecrets(keyMaterialBytes)\n        return MessageKeys(keyMaterial.getCipherKey(), keyMaterial.getMacKey(), keyMaterial.getIv(), self.index)\n\n    def getBaseMaterial(self, seedBytes):\n        mac = hmac.new(bytes(self.key), digestmod=hashlib.sha256)\n        mac.update(bytes(seedBytes))\n        return mac.digest()\n"
  },
  {
    "path": "axolotl/ratchet/ratchetingsession.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..ecc.curve import Curve\nfrom .bobaxolotlparamaters import BobAxolotlParameters\nfrom .aliceaxolotlparameters import AliceAxolotlParameters\nfrom ..kdf.hkdfv3 import HKDFv3\nfrom ..util.byteutil import ByteUtil\nfrom .rootkey import RootKey\nfrom .chainkey import ChainKey\nfrom ..protocol.ciphertextmessage import CiphertextMessage\n\n\nclass RatchetingSession:\n    @staticmethod\n    def initializeSession(sessionState, parameters):\n        \"\"\"\n        :type sessionState: SessionState\n        :type parameters: SymmetricAxolotlParameters\n        \"\"\"\n        if RatchetingSession.isAlice(parameters.getOurBaseKey().getPublicKey(), parameters.getTheirBaseKey()):\n            aliceParameters = AliceAxolotlParameters.newBuilder()\n            aliceParameters.setOurBaseKey(parameters.getOurBaseKey()) \\\n                .setOurIdentityKey(parameters.getOurIdentityKey()) \\\n                .setTheirRatchetKey(parameters.getTheirRatchetKey()) \\\n                .setTheirIdentityKey(parameters.getTheirIdentityKey()) \\\n                .setTheirSignedPreKey(parameters.getTheirBaseKey()) \\\n                .setTheirOneTimePreKey(None)\n            RatchetingSession.initializeSessionAsAlice(sessionState, aliceParameters.create())\n        else:\n            bobParameters = BobAxolotlParameters.newBuilder()\n            bobParameters.setOurIdentityKey(parameters.getOurIdentityKey()) \\\n                .setOurRatchetKey(parameters.getOurRatchetKey()) \\\n                .setOurSignedPreKey(parameters.getOurBaseKey()) \\\n                .setOurOneTimePreKey(None) \\\n                .setTheirBaseKey(parameters.getTheirBaseKey()) \\\n                .setTheirIdentityKey(parameters.getTheirIdentityKey())\n            RatchetingSession.initializeSessionAsBob(sessionState, bobParameters.create())\n\n    @staticmethod\n    def initializeSessionAsAlice(sessionState, parameters):\n        \"\"\"\n        :type sessionState: SessionState\n        :type parameters: AliceAxolotlParameters\n        \"\"\"\n        sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION)\n        sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey())\n        sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey())\n\n        sendingRatchetKey = Curve.generateKeyPair()\n        secrets = bytearray()\n\n        secrets.extend(RatchetingSession.getDiscontinuityBytes())\n\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),\n                                                parameters.getOurIdentityKey().getPrivateKey()))\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),\n                                                parameters.getOurBaseKey().getPrivateKey()))\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),\n                                                parameters.getOurBaseKey().getPrivateKey()))\n\n        if parameters.getTheirOneTimePreKey() is not None:\n            secrets.extend(Curve.calculateAgreement(parameters.getTheirOneTimePreKey(),\n                                                    parameters.getOurBaseKey().getPrivateKey()))\n\n        derivedKeys = RatchetingSession.calculateDerivedKeys(secrets)\n        sendingChain = derivedKeys.getRootKey().createChain(parameters.getTheirRatchetKey(), sendingRatchetKey)\n\n        sessionState.addReceiverChain(parameters.getTheirRatchetKey(), derivedKeys.getChainKey())\n        sessionState.setSenderChain(sendingRatchetKey, sendingChain[1])\n        sessionState.setRootKey(sendingChain[0])\n\n    @staticmethod\n    def initializeSessionAsBob(sessionState, parameters):\n        \"\"\"\n        :type sessionState: SessionState\n        :type parameters: BobAxolotlParameters\n        \"\"\"\n        sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION)\n        sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey())\n        sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey())\n\n        secrets = bytearray()\n\n        secrets.extend(RatchetingSession.getDiscontinuityBytes())\n\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),\n                                                parameters.getOurSignedPreKey().getPrivateKey()))\n\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirBaseKey(),\n                                                parameters.getOurIdentityKey().getPrivateKey()))\n        secrets.extend(Curve.calculateAgreement(parameters.getTheirBaseKey(),\n                                                parameters.getOurSignedPreKey().getPrivateKey()))\n\n        if parameters.getOurOneTimePreKey() is not None:\n            secrets.extend(Curve.calculateAgreement(parameters.getTheirBaseKey(),\n                                                    parameters.getOurOneTimePreKey().getPrivateKey()))\n\n        derivedKeys = RatchetingSession.calculateDerivedKeys(secrets)\n        sessionState.setSenderChain(parameters.getOurRatchetKey(), derivedKeys.getChainKey())\n        sessionState.setRootKey(derivedKeys.getRootKey())\n\n    @staticmethod\n    def getDiscontinuityBytes():\n        return bytearray([0xFF] * 32)\n\n    @staticmethod\n    def calculateDerivedKeys(masterSecret):\n        kdf = HKDFv3()\n        derivedSecretBytes = kdf.deriveSecrets(masterSecret,  bytearray(\"WhisperText\".encode()), 64)\n        derivedSecrets = ByteUtil.split(derivedSecretBytes, 32, 32)\n        return RatchetingSession.DerivedKeys(RootKey(kdf, derivedSecrets[0]),\n                                             ChainKey(kdf, derivedSecrets[1], 0))\n\n    @staticmethod\n    def isAlice(ourKey, theirKey):\n        \"\"\"\n        :type ourKey: ECPublicKey\n        :type theirKey: ECPublicKey\n        \"\"\"\n        return ourKey < theirKey\n\n    class DerivedKeys:\n        def __init__(self, rootKey, chainKey):\n            \"\"\"\n            :type rootKey: RootKey\n            :type  chainKey: ChainKey\n            \"\"\"\n            self.rootKey = rootKey\n            self.chainKey = chainKey\n\n        def getRootKey(self):\n            return self.rootKey\n\n        def getChainKey(self):\n            return self.chainKey\n"
  },
  {
    "path": "axolotl/ratchet/rootkey.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..ecc.curve import Curve\nfrom ..kdf.derivedrootsecrets import DerivedRootSecrets\nfrom .chainkey import ChainKey\n\n\nclass RootKey:\n    def __init__(self, kdf, key):\n        self.kdf = kdf\n        self.key = key\n\n    def getKeyBytes(self):\n        return self.key\n\n    def createChain(self, ECPublicKey_theirRatchetKey, ECKeyPair_ourRatchetKey):\n        sharedSecret = Curve.calculateAgreement(ECPublicKey_theirRatchetKey, ECKeyPair_ourRatchetKey.getPrivateKey())\n        derivedSecretBytes = self.kdf.deriveSecrets(sharedSecret,\n                                                    \"WhisperRatchet\".encode(),\n                                                    DerivedRootSecrets.SIZE,\n                                                    salt=self.key)\n        derivedSecrets = DerivedRootSecrets(derivedSecretBytes)\n        newRootKey = RootKey(self.kdf, derivedSecrets.getRootKey())\n        newChainKey = ChainKey(self.kdf, derivedSecrets.getChainKey(), 0)\n        return (newRootKey, newChainKey)\n"
  },
  {
    "path": "axolotl/ratchet/symmetricaxolotlparameters.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass SymmetricAxolotlParameters:\n    def __init__(self, ourBaseKey, ourRatchetKey, ourIdentityKey, theirBaseKey,\n                 theirRatchetKey, theirIdentityKey):\n        \"\"\"\n        :type ourBaseKey: ECKeyPair\n        :type ourRatchetKey: ECKeyPair\n        :type ourIdentityKey: IdentityKeyPair\n        :type theirBaseKey: ECPublicKey\n        :type theirRatchetKey: ECKeyPair\n        :type theirIdentityKey: IdentityKey\n        \"\"\"\n        self.ourBaseKey = ourBaseKey\n        self.ourIdentityKey = ourIdentityKey\n        self.ourRatchetKey = ourRatchetKey\n        self.theirRatchetKey = theirRatchetKey\n        self.theirIdentityKey = theirIdentityKey\n        self.theirBaseKey = theirBaseKey\n\n        if ourBaseKey is None or ourIdentityKey is None or ourRatchetKey is None \\\n                or theirRatchetKey is None or theirIdentityKey is None or theirBaseKey is None:\n            raise ValueError(\"Null value!\")\n\n    def getOurBaseKey(self):\n        return self.ourBaseKey\n\n    def getOurIdentityKey(self):\n        return self.ourIdentityKey\n\n    def getTheirRatchetKey(self):\n        return self.theirRatchetKey\n\n    def getTheirIdentityKey(self):\n        return self.theirIdentityKey\n\n    def getTheirBaseKey(self):\n        return self.theirBaseKey\n\n    def getOurRatchetKey(self):\n        return self.ourRatchetKey\n\n    @staticmethod\n    def newBuilder():\n        return SymmetricAxolotlParameters.Builder()\n\n    class Builder:\n        def __init__(self):\n            self.ourIdentityKey = None\n            self.ourBaseKey = None\n            self.ourRatchetKey = None\n            self.theirRatchetKey = None\n            self.theirIdentityKey = None\n            self.theirBaseKey = None\n\n        def setOurIdentityKey(self, ourIdentityKey):\n            self.ourIdentityKey = ourIdentityKey\n            return self\n\n        def setOurBaseKey(self, ourBaseKey):\n            self.ourBaseKey = ourBaseKey\n            return self\n\n        def setOurRatchetKey(self, ourRatchetKey):\n            self.ourRatchetKey = ourRatchetKey\n            return self\n\n        def setTheirRatchetKey(self, theirRatchetKey):\n            self.theirRatchetKey = theirRatchetKey\n            return self\n\n        def setTheirIdentityKey(self, theirIdentityKey):\n            self.theirIdentityKey = theirIdentityKey\n            return self\n\n        def setTheirBaseKey(self, theirBaseKey):\n            self.theirBaseKey = theirBaseKey\n            return self\n\n        def create(self):\n            return SymmetricAxolotlParameters(self.ourBaseKey, self.ourRatchetKey, self.ourIdentityKey,\n                                              self.theirBaseKey, self.theirRatchetKey, self.theirIdentityKey)\n"
  },
  {
    "path": "axolotl/sessionbuilder.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom .ecc.curve import Curve\nfrom .ratchet.aliceaxolotlparameters import AliceAxolotlParameters\nfrom .ratchet.bobaxolotlparamaters import BobAxolotlParameters\nfrom .ratchet.symmetricaxolotlparameters import SymmetricAxolotlParameters\nfrom .ratchet.ratchetingsession import RatchetingSession\nfrom .invalidkeyexception import InvalidKeyException\nfrom .invalidkeyidexception import InvalidKeyIdException\nfrom .untrustedidentityexception import UntrustedIdentityException\nfrom .protocol.keyexchangemessage import KeyExchangeMessage\nfrom .protocol.ciphertextmessage import CiphertextMessage\nfrom .statekeyexchangeexception import StaleKeyExchangeException\nfrom .util.medium import Medium\nfrom .util.keyhelper import KeyHelper\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SessionBuilder:\n    def __init__(self, sessionStore, preKeyStore, signedPreKeyStore, identityKeyStore, recepientId, deviceId):\n        self.sessionStore = sessionStore\n        self.preKeyStore = preKeyStore\n        self.signedPreKeyStore = signedPreKeyStore\n        self.identityKeyStore = identityKeyStore\n        self.recipientId = recepientId\n        self.deviceId = deviceId\n\n    def process(self, sessionRecord, message):\n        \"\"\"\n        :param sessionRecord:\n        :param message:\n        :type message: PreKeyWhisperMessage\n        \"\"\"\n\n        theirIdentityKey = message.getIdentityKey()\n\n        if not self.identityKeyStore.isTrustedIdentity(self.recipientId, theirIdentityKey):\n            raise UntrustedIdentityException(self.recipientId, theirIdentityKey)\n\n        unsignedPreKeyId = self.processV3(sessionRecord, message)\n\n        self.identityKeyStore.saveIdentity(self.recipientId, theirIdentityKey)\n\n        return unsignedPreKeyId\n\n    def processV3(self, sessionRecord, message):\n        \"\"\"\n        :param sessionRecord:\n        :param message:\n        :type message: PreKeyWhisperMessage\n        :return:\n        \"\"\"\n\n        if sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize()):\n            logger.warn(\"We've already setup a session for this V3 message, letting bundled message fall through...\")\n            return None\n\n        ourSignedPreKey = self.signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair()\n        parameters = BobAxolotlParameters.newBuilder()\n        parameters.setTheirBaseKey(message.getBaseKey())\\\n            .setTheirIdentityKey(message.getIdentityKey())\\\n            .setOurIdentityKey(self.identityKeyStore.getIdentityKeyPair())\\\n            .setOurSignedPreKey(ourSignedPreKey)\\\n            .setOurRatchetKey(ourSignedPreKey)\n\n        if message.getPreKeyId() is not None:\n            parameters.setOurOneTimePreKey(self.preKeyStore.loadPreKey(message.getPreKeyId()).getKeyPair())\n        else:\n            parameters.setOurOneTimePreKey(None)\n\n        if not sessionRecord.isFresh():\n            sessionRecord.archiveCurrentState()\n\n        RatchetingSession.initializeSessionAsBob(sessionRecord.getSessionState(), parameters.create())\n        sessionRecord.getSessionState().setLocalRegistrationId(self.identityKeyStore.getLocalRegistrationId())\n        sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId())\n        sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize())\n\n        if message.getPreKeyId() is not None and message.getPreKeyId() != Medium.MAX_VALUE:\n            return message.getPreKeyId()\n        else:\n            return None\n\n    def processPreKeyBundle(self, preKey):\n        \"\"\"\n        :type preKey: PreKeyBundle\n        \"\"\"\n        if not self.identityKeyStore.isTrustedIdentity(self.recipientId, preKey.getIdentityKey()):\n            raise UntrustedIdentityException(self.recipientId, preKey.getIdentityKey())\n\n        if preKey.getSignedPreKey() is not None and\\\n            not Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),\n                                      preKey.getSignedPreKey().serialize(),\n                                      preKey.getSignedPreKeySignature()):\n            raise InvalidKeyException(\"Invalid signature on device key!\")\n\n        if preKey.getSignedPreKey() is None:\n            raise InvalidKeyException(\"No signed prekey!!\")\n\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n        ourBaseKey = Curve.generateKeyPair()\n        theirSignedPreKey = preKey.getSignedPreKey()\n        theirOneTimePreKey = preKey.getPreKey()\n        theirOneTimePreKeyId = preKey.getPreKeyId() if theirOneTimePreKey is not None else None\n\n        parameters = AliceAxolotlParameters.newBuilder()\n\n        parameters.setOurBaseKey(ourBaseKey)\\\n            .setOurIdentityKey(self.identityKeyStore.getIdentityKeyPair())\\\n            .setTheirIdentityKey(preKey.getIdentityKey())\\\n            .setTheirSignedPreKey(theirSignedPreKey)\\\n            .setTheirRatchetKey(theirSignedPreKey)\\\n            .setTheirOneTimePreKey(theirOneTimePreKey)\n\n        if not sessionRecord.isFresh():\n            sessionRecord.archiveCurrentState()\n\n        RatchetingSession.initializeSessionAsAlice(sessionRecord.getSessionState(), parameters.create())\n\n        sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId,\n                                                                       preKey.getSignedPreKeyId(),\n                                                                       ourBaseKey.getPublicKey())\n        sessionRecord.getSessionState().setLocalRegistrationId(self.identityKeyStore.getLocalRegistrationId())\n        sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId())\n        sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize())\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n        self.identityKeyStore.saveIdentity(self.recipientId, preKey.getIdentityKey())\n\n    def processKeyExchangeMessage(self, keyExchangeMessage):\n\n        if not self.identityKeyStore.isTrustedIdentity(self.recipientId, keyExchangeMessage.getIdentityKey()):\n            raise UntrustedIdentityException(self.recipientId, keyExchangeMessage.getIdentityKey())\n\n        responseMessage = None\n\n        if keyExchangeMessage.isInitiate():\n            responseMessage = self.processInitiate(keyExchangeMessage)\n        else:\n            self.processResponse(keyExchangeMessage)\n\n        return responseMessage\n\n    def processInitiate(self, keyExchangeMessage):\n        flags = KeyExchangeMessage.RESPONSE_FLAG\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n\n        if not Curve.verifySignature(\n                keyExchangeMessage.getIdentityKey().getPublicKey(),\n                keyExchangeMessage.getBaseKey().serialize(),\n                keyExchangeMessage.getBaseKeySignature()):\n            raise InvalidKeyException(\"Bad signature!\")\n\n        builder = SymmetricAxolotlParameters.newBuilder()\n        if not sessionRecord.getSessionState().hasPendingKeyExchange():\n            builder.setOurIdentityKey(self.identityKeyStore.getIdentityKeyPair())\\\n                .setOurBaseKey(Curve.generateKeyPair())\\\n                .setOurRatchetKey(Curve.generateKeyPair())\n        else:\n            builder.setOurIdentityKey(sessionRecord.getSessionState().getPendingKeyExchangeIdentityKey())\\\n                .setOurBaseKey(sessionRecord.getSessionState().getPendingKeyExchangeBaseKey())\\\n                .setOurRatchetKey(sessionRecord.getSessionState().getPendingKeyExchangeRatchetKey())\n            flags |= KeyExchangeMessage.SIMULTAENOUS_INITIATE_FLAG\n\n        builder.setTheirBaseKey(keyExchangeMessage.getBaseKey())\\\n            .setTheirRatchetKey(keyExchangeMessage.getRatchetKey())\\\n            .setTheirIdentityKey(keyExchangeMessage.getIdentityKey())\n\n        parameters = builder.create()\n\n        if not sessionRecord.isFresh():\n            sessionRecord.archiveCurrentState()\n\n        RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters)\n\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n        self.identityKeyStore.saveIdentity(self.recipientId, keyExchangeMessage.getIdentityKey())\n\n        baseKeySignature = Curve.calculateSignature(parameters.getOurIdentityKey().getPrivateKey(),\n                                                    parameters.getOurBaseKey().getPublicKey().serialize())\n\n        return KeyExchangeMessage(sessionRecord.getSessionState().getSessionVersion(),\n                                  keyExchangeMessage.getSequence(), flags,\n                                  parameters.getOurBaseKey().getPublicKey(),\n                                  baseKeySignature, parameters.getOurRatchetKey().getPublicKey(),\n                                  parameters.getOurIdentityKey().getPublicKey())\n\n    def processResponse(self, keyExchangeMessage):\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n        sessionState = sessionRecord.getSessionState()\n        hasPendingKeyExchange = sessionState.hasPendingKeyExchange()\n        isSimultaneousInitiateResponse = keyExchangeMessage.isResponseForSimultaneousInitiate()\n\n        if not hasPendingKeyExchange \\\n                or sessionState.getPendingKeyExchangeSequence() != keyExchangeMessage.getSequence():\n            logger.warn(\"No matching sequence for response. \"\n                        \"Is simultaneous initiate response: %s\" % isSimultaneousInitiateResponse)\n            if not isSimultaneousInitiateResponse:\n                raise StaleKeyExchangeException()\n            else:\n                return\n\n        parameters = SymmetricAxolotlParameters.newBuilder()\n\n        parameters.setOurBaseKey(sessionRecord.getSessionState().getPendingKeyExchangeBaseKey())\\\n            .setOurRatchetKey(sessionRecord.getSessionState().getPendingKeyExchangeRatchetKey())\\\n            .setOurIdentityKey(sessionRecord.getSessionState().getPendingKeyExchangeIdentityKey())\\\n            .setTheirBaseKey(keyExchangeMessage.getBaseKey())\\\n            .setTheirRatchetKey(keyExchangeMessage.getRatchetKey())\\\n            .setTheirIdentityKey(keyExchangeMessage.getIdentityKey())\n\n        if not sessionRecord.isFresh():\n            sessionRecord.archiveCurrentState()\n\n        RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create())\n\n        if not Curve.verifySignature(\n                keyExchangeMessage.getIdentityKey().getPublicKey(),\n                keyExchangeMessage.getBaseKey().serialize(),\n                keyExchangeMessage.getBaseKeySignature()):\n            raise InvalidKeyException(\"Base key signature doesn't match!\")\n\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n        self.identityKeyStore.saveIdentity(self.recipientId, keyExchangeMessage.getIdentityKey())\n\n    def processInitKeyExchangeMessage(self):\n        try:\n            sequence = KeyHelper.getRandomSequence(65534) + 1\n            flags = KeyExchangeMessage.INITIATE_FLAG\n            baseKey = Curve.generateKeyPair()\n            ratchetKey = Curve.generateKeyPair()\n            identityKey = self.identityKeyStore.getIdentityKeyPair()\n            baseKeySignature = Curve.calculateSignature(identityKey.getPrivateKey(), baseKey.getPublicKey().serialize())\n            sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n\n            sessionRecord.getSessionState().setPendingKeyExchange(sequence, baseKey, ratchetKey, identityKey)\n            self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n\n            return KeyExchangeMessage(CiphertextMessage.CURRENT_VERSION, sequence, flags, baseKey.getPublicKey(), baseKeySignature,\n                                      ratchetKey.getPublicKey(), identityKey.getPublicKey())\n        except InvalidKeyException as e:\n            raise AssertionError(e)\n"
  },
  {
    "path": "axolotl/sessioncipher.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import padding\n\nfrom .ecc.curve import Curve\nfrom .sessionbuilder import SessionBuilder\nfrom .state.sessionstate import SessionState\nfrom .protocol.whispermessage import WhisperMessage\nfrom .protocol.prekeywhispermessage import PreKeyWhisperMessage\nfrom .nosessionexception import NoSessionException\nfrom .invalidmessageexception import InvalidMessageException\nfrom .duplicatemessagexception import DuplicateMessageException\n\nimport  logging\n\nlogger = logging.getLogger(__name__)\n\nclass SessionCipher:\n    def __init__(self, sessionStore, preKeyStore, signedPreKeyStore, identityKeyStore, recepientId, deviceId):\n        self.sessionStore = sessionStore\n        self.preKeyStore = preKeyStore\n        self.recipientId = recepientId\n        self.deviceId = deviceId\n        self.sessionBuilder = SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,\n                                             identityKeyStore, recepientId, deviceId)\n\n    def encrypt(self, paddedMessage):\n        \"\"\"\n        :type paddedMessage: bytes\n        \"\"\"\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n        sessionState = sessionRecord.getSessionState()\n        chainKey = sessionState.getSenderChainKey()\n        messageKeys = chainKey.getMessageKeys()\n        senderEphemeral = sessionState.getSenderRatchetKey()\n        previousCounter = sessionState.getPreviousCounter()\n        sessionVersion = sessionState.getSessionVersion()\n\n        ciphertextBody = self.getCiphertext(sessionVersion, messageKeys, paddedMessage)\n        ciphertextMessage = WhisperMessage(sessionVersion, messageKeys.getMacKey(),\n                                           senderEphemeral, chainKey.getIndex(),\n                                           previousCounter, ciphertextBody,\n                                           sessionState.getLocalIdentityKey(),\n                                           sessionState.getRemoteIdentityKey())\n\n        if sessionState.hasUnacknowledgedPreKeyMessage():\n            items = sessionState.getUnacknowledgedPreKeyMessageItems()\n            localRegistrationid = sessionState.getLocalRegistrationId()\n\n            ciphertextMessage = PreKeyWhisperMessage(sessionVersion, localRegistrationid, items.getPreKeyId(),\n                                                     items.getSignedPreKeyId(), items.getBaseKey(),\n                                                     sessionState.getLocalIdentityKey(),\n                                                     ciphertextMessage)\n        sessionState.setSenderChainKey(chainKey.getNextChainKey())\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n\n        return ciphertextMessage\n\n    def decryptMsg(self, ciphertext, textMsg=True):\n        \"\"\"\n        :type ciphertext: WhisperMessage\n        :type textMsg: Bool set this to False if you are decrypting bytes\n                       instead of string\n        \"\"\"\n\n        if not self.sessionStore.containsSession(self.recipientId, self.deviceId):\n            raise NoSessionException(\"No session for: %s, %s\" % (self.recipientId, self.deviceId))\n\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n        plaintext = self.decryptWithSessionRecord(sessionRecord, ciphertext)\n\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n\n        return plaintext\n\n    def decryptPkmsg(self, ciphertext, textMsg=True):\n        \"\"\"\n        :type ciphertext: PreKeyWhisperMessage\n        \"\"\"\n        sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)\n        unsignedPreKeyId = self.sessionBuilder.process(sessionRecord, ciphertext)\n        plaintext = self.decryptWithSessionRecord(sessionRecord, ciphertext.getWhisperMessage())\n\n        # callback.handlePlaintext(plaintext)\n        self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)\n\n        if unsignedPreKeyId is not None:\n            self.preKeyStore.removePreKey(unsignedPreKeyId)\n\n        return plaintext\n\n    def decryptWithSessionRecord(self, sessionRecord, cipherText):\n        \"\"\"\n        :type sessionRecord: SessionRecord\n        :type cipherText: WhisperMessage\n        \"\"\"\n\n        previousStates = sessionRecord.getPreviousSessionStates()\n        exceptions = []\n        try:\n            sessionState = SessionState(sessionRecord.getSessionState())\n            plaintext = self.decryptWithSessionState(sessionState, cipherText)\n            sessionRecord.setState(sessionState)\n            return plaintext\n        except InvalidMessageException as e:\n            exceptions.append(e)\n\n        for i in range(0, len(previousStates)):\n            previousState = previousStates[i]\n            try:\n                promotedState = SessionState(previousState)\n                plaintext = self.decryptWithSessionState(promotedState, cipherText)\n                previousStates.pop(i)\n                sessionRecord.promoteState(promotedState)\n                return plaintext\n            except InvalidMessageException as e:\n                exceptions.append(e)\n\n        raise InvalidMessageException(\"No valid sessions\", exceptions)\n\n    def decryptWithSessionState(self, sessionState, ciphertextMessage):\n\n        if not sessionState.hasSenderChain():\n            raise InvalidMessageException(\"Uninitialized session!\")\n\n        if ciphertextMessage.getMessageVersion() != sessionState.getSessionVersion():\n            raise InvalidMessageException(\"Message version %s, but session version %s\" % (ciphertextMessage.getMessageVersion, sessionState.getSessionVersion()))\n\n        messageVersion = ciphertextMessage.getMessageVersion()\n        theirEphemeral = ciphertextMessage.getSenderRatchetKey()\n        counter = ciphertextMessage.getCounter()\n        chainKey = self.getOrCreateChainKey(sessionState, theirEphemeral)\n        messageKeys = self.getOrCreateMessageKeys(sessionState, theirEphemeral, chainKey, counter)\n\n        ciphertextMessage.verifyMac(messageVersion,\n                                    sessionState.getRemoteIdentityKey(),\n                                    sessionState.getLocalIdentityKey(),\n                                    messageKeys.getMacKey())\n\n        plaintext = self.getPlaintext(messageVersion, messageKeys, ciphertextMessage.getBody())\n        sessionState.clearUnacknowledgedPreKeyMessage()\n\n        return plaintext\n\n    def getOrCreateChainKey(self, sessionState, ECPublickKey_theirEphemeral):\n        theirEphemeral = ECPublickKey_theirEphemeral\n        if sessionState.hasReceiverChain(theirEphemeral):\n            return sessionState.getReceiverChainKey(theirEphemeral)\n        else:\n            rootKey = sessionState.getRootKey()\n            ourEphemeral = sessionState.getSenderRatchetKeyPair()\n            receiverChain = rootKey.createChain(theirEphemeral, ourEphemeral)\n            ourNewEphemeral = Curve.generateKeyPair()\n            senderChain = receiverChain[0].createChain(theirEphemeral, ourNewEphemeral)\n\n            sessionState.setRootKey(senderChain[0])\n            sessionState.addReceiverChain(theirEphemeral, receiverChain[1])\n            sessionState.setPreviousCounter(max(sessionState.getSenderChainKey().getIndex() - 1, 0))\n            sessionState.setSenderChain(ourNewEphemeral, senderChain[1])\n            return receiverChain[1]\n\n    def getOrCreateMessageKeys(self, sessionState, ECPublicKey_theirEphemeral, chainKey, counter):\n        theirEphemeral = ECPublicKey_theirEphemeral\n        if chainKey.getIndex() > counter:\n            if sessionState.hasMessageKeys(theirEphemeral, counter):\n                return sessionState.removeMessageKeys(theirEphemeral, counter)\n            else:\n                raise DuplicateMessageException(\"Received message with old counter: %s, %s\" % (chainKey.getIndex(),\n                                                                                               counter))\n\n        if counter - chainKey.getIndex() > 2000:\n            raise InvalidMessageException(\"Over 2000 messages into the future!\")\n\n        while chainKey.getIndex() < counter:\n            messageKeys = chainKey.getMessageKeys()\n            sessionState.setMessageKeys(theirEphemeral, messageKeys)\n            chainKey = chainKey.getNextChainKey()\n\n        sessionState.setReceiverChainKey(theirEphemeral, chainKey.getNextChainKey())\n        return chainKey.getMessageKeys()\n\n    def getCiphertext(self, version, messageKeys, plainText):\n        \"\"\"\n        :type version: int\n        :type messageKeys: MessageKeys\n        :type  plainText: bytearray\n        \"\"\"\n        cipher = self.getCipher(messageKeys.getCipherKey(), messageKeys.getIv())\n        return cipher.encrypt(plainText)\n\n    def getPlaintext(self, version, messageKeys, cipherText):\n        cipher = self.getCipher(messageKeys.getCipherKey(), messageKeys.getIv())\n\n        return cipher.decrypt(cipherText)\n\n    def getCipher(self, key, iv):\n        return AESCipher(key, iv)\n\nclass AESCipher:\n    def __init__(self, key, iv):\n        self.key = key\n        self.iv = iv\n        self.cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())\n\n    def encrypt(self, raw):\n        padder = padding.PKCS7(128).padder()\n        rawPadded = padder.update(raw) + padder.finalize()\n\n        encryptor = self.cipher.encryptor()\n        try:\n            return encryptor.update(rawPadded) + encryptor.finalize()\n        except ValueError:\n            raise\n\n    def decrypt(self, enc):\n        decryptor = self.cipher.decryptor()\n        decrypted = decryptor.update(enc) + decryptor.finalize()\n        unpadder = padding.PKCS7(128).unpadder()\n        return unpadder.update(decrypted) + unpadder.finalize()\n"
  },
  {
    "path": "axolotl/state/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/state/axolotlstore.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\nfrom .identitykeystore import IdentityKeyStore\nfrom .prekeystore import PreKeyStore\nfrom .sessionstore import SessionStore\nfrom .signedprekeystore import SignedPreKeyStore\n\n\nclass AxolotlStore(IdentityKeyStore, PreKeyStore, SignedPreKeyStore, SessionStore):\n    __metaclass__ = abc.ABCMeta\n"
  },
  {
    "path": "axolotl/state/identitykeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass IdentityKeyStore(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def getIdentityKeyPair(self):\n        pass\n\n    @abc.abstractmethod\n    def getLocalRegistrationId(self):\n        pass\n\n    @abc.abstractmethod\n    def saveIdentity(self, recepientId, identityKey):\n        pass\n\n    @abc.abstractmethod\n    def isTrustedIdentity(self, recepientId, identityKey):\n        pass\n"
  },
  {
    "path": "axolotl/state/prekeybundle.py",
    "content": "# -*- cosing: utf-8 -*-\n\n\nclass PreKeyBundle:\n    def __init__(self, registrationId, deviceId, preKeyId, ECPublicKey_preKeyPublic,\n                 signedPreKeyId, ECPublicKey_signedPreKeyPublic, signedPreKeySignature,\n                 identityKey):\n        self.registrationId = registrationId\n        self.deviceId = deviceId\n        self.preKeyId = preKeyId\n        self.preKeyPublic = ECPublicKey_preKeyPublic\n        self.signedPreKeyId = signedPreKeyId\n        self.signedPreKeyPublic = ECPublicKey_signedPreKeyPublic\n        self.signedPreKeySignature = signedPreKeySignature\n        self.identityKey = identityKey\n\n    def getDeviceId(self):\n        return self.deviceId\n\n    def getPreKeyId(self):\n        return self.preKeyId\n\n    def getPreKey(self):\n        return self.preKeyPublic\n\n    def getSignedPreKeyId(self):\n        return self.signedPreKeyId\n\n    def getSignedPreKey(self):\n        return self.signedPreKeyPublic\n\n    def getSignedPreKeySignature(self):\n        return self.signedPreKeySignature\n\n    def getIdentityKey(self):\n        return self.identityKey\n\n    def getRegistrationId(self):\n        return self.registrationId\n"
  },
  {
    "path": "axolotl/state/prekeyrecord.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom .storageprotos_pb2 import PreKeyRecordStructure\nfrom ..ecc.curve import Curve\nfrom ..ecc.eckeypair import ECKeyPair\n\n\nclass PreKeyRecord:\n    def __init__(self, _id=None, ecKeyPair=None, serialized=None):\n        self.structure = PreKeyRecordStructure()\n        if serialized:\n            self.structure.ParseFromString(serialized)\n        else:\n            self.structure.id = _id\n            self.structure.publicKey = ecKeyPair.getPublicKey().serialize()\n            self.structure.privateKey = ecKeyPair.getPrivateKey().serialize()\n\n    def getId(self):\n        return self.structure.id\n\n    def getKeyPair(self):\n        publicKey = Curve.decodePoint(bytearray(self.structure.publicKey), 0)\n        privateKey = Curve.decodePrivatePoint(bytearray(self.structure.privateKey))\n        return ECKeyPair(publicKey, privateKey)\n\n    def serialize(self):\n        return self.structure.SerializeToString()\n"
  },
  {
    "path": "axolotl/state/prekeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass PreKeyStore(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def loadPreKey(self, preKeyId):\n        pass\n\n    @abc.abstractmethod\n    def storePreKey(self, preKeyId, preKeyRecord):\n        pass\n\n    @abc.abstractmethod\n    def containsPreKey(self, preKeyId):\n        pass\n\n    @abc.abstractmethod\n    def removePreKey(self, preKeyId):\n        pass\n"
  },
  {
    "path": "axolotl/state/sessionrecord.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom . import storageprotos_pb2 as storageprotos\nfrom .sessionstate import SessionState\n\n\nclass SessionRecord:\n    ARCHIVED_STATES_MAX_LENGTH = 40\n\n    def __init__(self, sessionState=None, serialized=None):\n        \"\"\"\n        :type sessionState: SessionState\n        :type serialized: str\n        \"\"\"\n        self.previousStates = []\n        if sessionState:\n            self.sessionState = sessionState\n            self.fresh = False\n        elif serialized:\n            record = storageprotos.RecordStructure()\n            record.ParseFromString(serialized)\n            self.sessionState = SessionState(record.currentSession)\n            self.fresh = False\n            for previousStructure in record.previousSessions:\n                self.previousStates.append(SessionState(previousStructure))\n\n        else:\n            self.fresh = True\n            self.sessionState = SessionState()\n\n    def hasSessionState(self, version, aliceBaseKey):\n        if self.sessionState.getSessionVersion() == version and aliceBaseKey == self.sessionState.getAliceBaseKey():\n            return True\n\n        for state in self.previousStates:\n            if state.getSessionVersion() == version and aliceBaseKey == state.getAliceBaseKey():\n                return True\n\n        return False\n\n    def getSessionState(self):\n        return self.sessionState\n\n    def getPreviousSessionStates(self):\n        return self.previousStates\n\n    def isFresh(self):\n        return self.fresh\n\n    def archiveCurrentState(self):\n        self.promoteState(SessionState())\n\n    def promoteState(self, promotedState):\n        self.previousStates.insert(0, self.sessionState)\n        self.sessionState = promotedState\n        if len(self.previousStates) > self.__class__.ARCHIVED_STATES_MAX_LENGTH:\n            self.previousStates.pop()\n\n    def setState(self, sessionState):\n        self.sessionState = sessionState\n\n    def serialize(self):\n        previousStructures = [previousState.getStructure() for previousState in self.previousStates]\n        record = storageprotos.RecordStructure()\n        record.currentSession.MergeFrom(self.sessionState.getStructure())\n        record.previousSessions.extend(previousStructures)\n\n        return record.SerializeToString()\n"
  },
  {
    "path": "axolotl/state/sessionstate.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom . import storageprotos_pb2 as storageprotos\nfrom ..identitykeypair import IdentityKey, IdentityKeyPair\nfrom ..ratchet.rootkey import RootKey\nfrom ..kdf.hkdf import HKDF\nfrom ..ecc.curve import Curve\nfrom ..ecc.eckeypair import ECKeyPair\nfrom ..ratchet.chainkey import ChainKey\nfrom ..kdf.messagekeys import MessageKeys\n\n\nclass SessionState:\n    def __init__(self, session=None):\n        if session is None:\n            self.sessionStructure = storageprotos.SessionStructure()\n        elif session.__class__ == SessionState:\n            self.sessionStructure = storageprotos.SessionStructure()\n            self.sessionStructure.CopyFrom(session.sessionStructure)\n        else:\n            self.sessionStructure = session\n\n    def getStructure(self):\n        return self.sessionStructure\n\n    def getAliceBaseKey(self):\n        return self.sessionStructure.aliceBaseKey\n\n    def setAliceBaseKey(self, aliceBaseKey):\n        self.sessionStructure.aliceBaseKey = aliceBaseKey\n\n    def setSessionVersion(self, version):\n        self.sessionStructure.sessionVersion = version\n\n    def getSessionVersion(self):\n        sessionVersion = self.sessionStructure.sessionVersion\n        return 2 if sessionVersion == 0 else sessionVersion\n\n    def setRemoteIdentityKey(self, identityKey):\n        self.sessionStructure.remoteIdentityPublic = identityKey.serialize()\n\n    def setLocalIdentityKey(self, identityKey):\n        self.sessionStructure.localIdentityPublic = identityKey.serialize()\n\n    def getRemoteIdentityKey(self):\n        if self.sessionStructure.remoteIdentityPublic is None:\n            return None\n        return IdentityKey(self.sessionStructure.remoteIdentityPublic, 0)\n\n    def getLocalIdentityKey(self):\n        return IdentityKey(self.sessionStructure.localIdentityPublic, 0)\n\n    def getPreviousCounter(self):\n        return self.sessionStructure.previousCounter\n\n    def setPreviousCounter(self, previousCounter):\n        self.sessionStructure.previousCounter = previousCounter\n\n    def getRootKey(self):\n        return RootKey(HKDF.createFor(self.getSessionVersion()), self.sessionStructure.rootKey)\n\n    def setRootKey(self, rootKey):\n        self.sessionStructure.rootKey = rootKey.getKeyBytes()\n\n    def getSenderRatchetKey(self):\n        return Curve.decodePoint(bytearray(self.sessionStructure.senderChain.senderRatchetKey), 0)\n\n    def getSenderRatchetKeyPair(self):\n        publicKey = self.getSenderRatchetKey()\n        privateKey = Curve.decodePrivatePoint(self.sessionStructure.senderChain.senderRatchetKeyPrivate)\n\n        return ECKeyPair(publicKey, privateKey)\n\n    def hasReceiverChain(self, ECPublickKey_senderEphemeral):\n        return self.getReceiverChain(ECPublickKey_senderEphemeral) is not None\n\n    def hasSenderChain(self):\n        return self.sessionStructure.HasField(\"senderChain\")\n\n    def getReceiverChain(self, ECPublickKey_senderEphemeral):\n        receiverChains = self.sessionStructure.receiverChains\n        index = 0\n        for receiverChain in receiverChains:\n            chainSenderRatchetKey = Curve.decodePoint(bytearray(receiverChain.senderRatchetKey), 0)\n            if chainSenderRatchetKey == ECPublickKey_senderEphemeral:\n                return (receiverChain, index)\n\n            index += 1\n\n    def getReceiverChainKey(self, ECPublicKey_senderEphemeral):\n        receiverChainAndIndex = self.getReceiverChain(ECPublicKey_senderEphemeral)\n        receiverChain = receiverChainAndIndex[0]\n        if receiverChain is None:\n            return None\n\n        return ChainKey(HKDF.createFor(self.getSessionVersion()),\n                        receiverChain.chainKey.key,\n                        receiverChain.chainKey.index)\n\n    def addReceiverChain(self, ECPublickKey_senderRatchetKey, chainKey):\n        senderRatchetKey = ECPublickKey_senderRatchetKey\n\n        chain = storageprotos.SessionStructure.Chain()\n        chain.senderRatchetKey = senderRatchetKey.serialize()\n        chain.chainKey.key = chainKey.getKey()\n        chain.chainKey.index = chainKey.getIndex()\n\n        self.sessionStructure.receiverChains.extend([chain])\n\n        if len(self.sessionStructure.receiverChains) > 5:\n            del self.sessionStructure.receiverChains[0]\n\n    def setSenderChain(self, ECKeyPair_senderRatchetKeyPair, chainKey):\n        senderRatchetKeyPair = ECKeyPair_senderRatchetKeyPair\n\n        # TODO: This is never used, maybe a bug?\n        senderChain = storageprotos.SessionStructure.Chain()\n\n        self.sessionStructure.senderChain.senderRatchetKey = senderRatchetKeyPair.getPublicKey().serialize()\n        self.sessionStructure.senderChain.senderRatchetKeyPrivate = senderRatchetKeyPair.getPrivateKey().serialize()\n        self.sessionStructure.senderChain.chainKey.key = chainKey.key\n        self.sessionStructure.senderChain.chainKey.index = chainKey.index\n\n    def getSenderChainKey(self):\n        chainKeyStructure = self.sessionStructure.senderChain.chainKey\n        return ChainKey(HKDF.createFor(self.getSessionVersion()),\n                        chainKeyStructure.key, chainKeyStructure.index)\n\n    def setSenderChainKey(self, ChainKey_nextChainKey):\n        nextChainKey = ChainKey_nextChainKey\n\n        self.sessionStructure.senderChain.chainKey.key = nextChainKey.getKey()\n        self.sessionStructure.senderChain.chainKey.index = nextChainKey.getIndex()\n\n    def hasMessageKeys(self, ECPublickKey_senderEphemeral, counter):\n        senderEphemeral = ECPublickKey_senderEphemeral\n        chainAndIndex = self.getReceiverChain(senderEphemeral)\n        chain = chainAndIndex[0]\n        if chain is None:\n            return False\n\n        messageKeyList = chain.messageKeys\n        for messageKey in messageKeyList:\n            if messageKey.index == counter:\n                return True\n\n        return False\n\n    def removeMessageKeys(self, ECPublicKey_senderEphemeral, counter):\n        senderEphemeral = ECPublicKey_senderEphemeral\n        chainAndIndex = self.getReceiverChain(senderEphemeral)\n        chain = chainAndIndex[0]\n        if chain is None:\n            return None\n\n        messageKeyList = chain.messageKeys\n        result = None\n\n        for i in range(0, len(messageKeyList)):\n            messageKey = messageKeyList[i]\n            if messageKey.index == counter:\n                result = MessageKeys(messageKey.cipherKey, messageKey.macKey, messageKey.iv, messageKey.index)\n                del messageKeyList[i]\n                break\n\n        self.sessionStructure.receiverChains[chainAndIndex[1]].CopyFrom(chain)\n\n        return result\n\n    def setMessageKeys(self, ECPublicKey_senderEphemeral, messageKeys):\n        senderEphemeral = ECPublicKey_senderEphemeral\n        chainAndIndex = self.getReceiverChain(senderEphemeral)\n        chain = chainAndIndex[0]\n        messageKeyStructure = chain.messageKeys.add()  # storageprotos.SessionStructure.Chain.MessageKey()\n        messageKeyStructure.cipherKey = messageKeys.getCipherKey()\n        messageKeyStructure.macKey = messageKeys.getMacKey()\n        messageKeyStructure.index = messageKeys.getCounter()\n        messageKeyStructure.iv = messageKeys.getIv()\n\n        # chain.messageKeys.append(messageKeyStructure)\n\n        self.sessionStructure.receiverChains[chainAndIndex[1]].CopyFrom(chain)\n\n    def setReceiverChainKey(self, ECPublicKey_senderEphemeral, chainKey):\n        senderEphemeral = ECPublicKey_senderEphemeral\n        chainAndIndex = self.getReceiverChain(senderEphemeral)\n        chain = chainAndIndex[0]\n        chain.chainKey.key = chainKey.getKey()\n        chain.chainKey.index = chainKey.getIndex()\n\n        # self.sessionStructure.receiverChains[chainAndIndex[1]].ClearField()\n        self.sessionStructure.receiverChains[chainAndIndex[1]].CopyFrom(chain)\n\n    def setPendingKeyExchange(self, sequence, ourBaseKey, ourRatchetKey, ourIdentityKey):\n        \"\"\"\n        :type sequence: int\n        :type ourBaseKey: ECKeyPair\n        :type ourRatchetKey: ECKeyPair\n        :type  ourIdentityKey: IdentityKeyPair\n        \"\"\"\n        structure = self.sessionStructure.PendingKeyExchange()\n        structure.sequence = sequence\n        structure.localBaseKey = ourBaseKey.getPublicKey().serialize()\n        structure.localBaseKeyPrivate = ourBaseKey.getPrivateKey().serialize()\n        structure.localRatchetKey = ourRatchetKey.getPublicKey().serialize()\n        structure.localRatchetKeyPrivate = ourRatchetKey.getPrivateKey().serialize()\n        structure.localIdentityKey = ourIdentityKey.getPublicKey().serialize()\n        structure.localIdentityKeyPrivate = ourIdentityKey.getPrivateKey().serialize()\n\n        self.sessionStructure.pendingKeyExchange.MergeFrom(structure)\n\n    def getPendingKeyExchangeSequence(self):\n        return self.sessionStructure.pendingKeyExchange.sequence\n\n    def getPendingKeyExchangeBaseKey(self):\n        publicKey = Curve.decodePoint(bytearray(self.sessionStructure.pendingKeyExchange.localBaseKey), 0)\n        privateKey = Curve.decodePrivatePoint(self.sessionStructure.pendingKeyExchange.localBaseKeyPrivate)\n        return ECKeyPair(publicKey, privateKey)\n\n    def getPendingKeyExchangeRatchetKey(self):\n        publicKey = Curve.decodePoint(bytearray(self.sessionStructure.pendingKeyExchange.localRatchetKey), 0)\n        privateKey = Curve.decodePrivatePoint(self.sessionStructure.pendingKeyExchange.localRatchetKeyPrivate)\n        return ECKeyPair(publicKey, privateKey)\n\n    def getPendingKeyExchangeIdentityKey(self):\n        publicKey = IdentityKey(bytearray(self.sessionStructure.pendingKeyExchange.localIdentityKey), 0)\n\n        privateKey = Curve.decodePrivatePoint(self.sessionStructure.pendingKeyExchange.localIdentityKeyPrivate)\n        return IdentityKeyPair(publicKey, privateKey)\n\n    def hasPendingKeyExchange(self):\n        return self.sessionStructure.HasField(\"pendingKeyExchange\")\n\n    def setUnacknowledgedPreKeyMessage(self, preKeyId, signedPreKeyId, baseKey):\n        \"\"\"\n        :type preKeyId: int\n        :type signedPreKeyId: int\n        :type baseKey: ECPublicKey\n        \"\"\"\n        self.sessionStructure.pendingPreKey.signedPreKeyId = signedPreKeyId\n        self.sessionStructure.pendingPreKey.baseKey = baseKey.serialize()\n\n        if preKeyId is not None:\n            self.sessionStructure.pendingPreKey.preKeyId = preKeyId\n\n    def hasUnacknowledgedPreKeyMessage(self):\n        return self.sessionStructure.HasField(\"pendingPreKey\")\n\n    def getUnacknowledgedPreKeyMessageItems(self):\n        preKeyId = None\n        if self.sessionStructure.pendingPreKey.HasField(\"preKeyId\"):\n            preKeyId = self.sessionStructure.pendingPreKey.preKeyId\n\n        return SessionState.UnacknowledgedPreKeyMessageItems(preKeyId,\n                                                             self.sessionStructure.pendingPreKey.signedPreKeyId,\n                                                             Curve.decodePoint(bytearray(self.sessionStructure.pendingPreKey.baseKey), 0))\n\n    def clearUnacknowledgedPreKeyMessage(self):\n        self.sessionStructure.ClearField(\"pendingPreKey\")\n\n    def setRemoteRegistrationId(self, registrationId):\n        self.sessionStructure.remoteRegistrationId = registrationId\n\n    def getRemoteRegistrationId(self, registrationId):\n        return self.sessionStructure.remoteRegistrationId\n\n    def setLocalRegistrationId(self, registrationId):\n        self.sessionStructure.localRegistrationId = registrationId\n\n    def getLocalRegistrationId(self):\n        return self.sessionStructure.localRegistrationId\n\n    def serialize(self):\n        return self.sessionStructure.SerializeToString()\n\n    class UnacknowledgedPreKeyMessageItems:\n        def __init__(self, preKeyId, signedPreKeyId, baseKey):\n            \"\"\"\n            :type preKeyId: int\n            :type signedPreKeyId: int\n            :type baseKey: ECPublicKey\n            \"\"\"\n            self.preKeyId = preKeyId\n            self.signedPreKeyId = signedPreKeyId\n            self.baseKey = baseKey\n\n        def getPreKeyId(self):\n            return self.preKeyId\n\n        def getSignedPreKeyId(self):\n            return self.signedPreKeyId\n\n        def getBaseKey(self):\n            return self.baseKey\n"
  },
  {
    "path": "axolotl/state/sessionstore.py",
    "content": "# -*- cosing: utf-8 -*-\n\nimport abc\n\n\nclass SessionStore(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def loadSession(self, recepientId, deviceId):\n        pass\n\n    @abc.abstractmethod\n    def getSubDeviceSessions(self, recepientId):\n        pass\n\n    @abc.abstractmethod\n    def storeSession(self, recepientId, deviceId, sessionRecord):\n        pass\n\n    @abc.abstractmethod\n    def containsSession(self, recepientId, deviceId):\n        pass\n\n    @abc.abstractmethod\n    def deleteSession(self, recepientId, deviceId):\n        pass\n\n    @abc.abstractmethod\n    def deleteAllSessions(self, recepientId):\n        pass\n"
  },
  {
    "path": "axolotl/state/signedprekeyrecord.py",
    "content": "# -*- coding; utf-8 -*-\n\nfrom .storageprotos_pb2 import SignedPreKeyRecordStructure\nfrom ..ecc.curve import Curve\nfrom ..ecc.eckeypair import ECKeyPair\n\n\nclass SignedPreKeyRecord:\n    def __init__(self, _id=None, timestamp=None, ecKeyPair=None, signature=None, serialized=None):\n        self.structure = SignedPreKeyRecordStructure()\n        if serialized:\n            self.structure.ParseFromString(serialized)\n        else:\n            self.structure.id = _id\n            self.structure.publicKey = ecKeyPair.getPublicKey().serialize()\n            self.structure.privateKey = ecKeyPair.getPrivateKey().serialize()\n            self.structure.signature = signature\n            self.structure.timestamp = timestamp\n\n    def getId(self):\n        return self.structure.id\n\n    def getTimestamp(self):\n        return self.structure.timestamp\n\n    def getKeyPair(self):\n        publicKey = Curve.decodePoint(bytearray(self.structure.publicKey), 0)\n        privateKey = Curve.decodePrivatePoint(bytearray(self.structure.privateKey))\n\n        return ECKeyPair(publicKey, privateKey)\n\n    def getSignature(self):\n        return self.structure.signature\n\n    def serialize(self):\n        return self.structure.SerializeToString()\n"
  },
  {
    "path": "axolotl/state/signedprekeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport abc\n\n\nclass SignedPreKeyStore(object):\n    __metaclass__ = abc.ABCMeta\n\n    @abc.abstractmethod\n    def loadSignedPreKey(self, signedPreKeyId):\n        pass\n\n    @abc.abstractmethod\n    def loadSignedPreKeys(self):\n        pass\n\n    @abc.abstractmethod\n    def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):\n        pass\n\n    @abc.abstractmethod\n    def containsSignedPreKey(self, signedPreKeyId):\n        pass\n\n    @abc.abstractmethod\n    def removeSignedPreKey(self, signedPreKeyId):\n        pass\n"
  },
  {
    "path": "axolotl/state/storageprotos_pb2.py",
    "content": "# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: LocalStorageProtocol.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import reflection as _reflection\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf import descriptor_pb2\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor.FileDescriptor(\n  name='LocalStorageProtocol.proto',\n  package='textsecure',\n  serialized_pb=_b('\\n\\x1aLocalStorageProtocol.proto\\x12\\ntextsecure\\\"\\xd3\\x08\\n\\x10SessionStructure\\x12\\x16\\n\\x0esessionVersion\\x18\\x01 \\x01(\\r\\x12\\x1b\\n\\x13localIdentityPublic\\x18\\x02 \\x01(\\x0c\\x12\\x1c\\n\\x14remoteIdentityPublic\\x18\\x03 \\x01(\\x0c\\x12\\x0f\\n\\x07rootKey\\x18\\x04 \\x01(\\x0c\\x12\\x17\\n\\x0fpreviousCounter\\x18\\x05 \\x01(\\r\\x12\\x37\\n\\x0bsenderChain\\x18\\x06 \\x01(\\x0b\\x32\\\".textsecure.SessionStructure.Chain\\x12:\\n\\x0ereceiverChains\\x18\\x07 \\x03(\\x0b\\x32\\\".textsecure.SessionStructure.Chain\\x12K\\n\\x12pendingKeyExchange\\x18\\x08 \\x01(\\x0b\\x32/.textsecure.SessionStructure.PendingKeyExchange\\x12\\x41\\n\\rpendingPreKey\\x18\\t \\x01(\\x0b\\x32*.textsecure.SessionStructure.PendingPreKey\\x12\\x1c\\n\\x14remoteRegistrationId\\x18\\n \\x01(\\r\\x12\\x1b\\n\\x13localRegistrationId\\x18\\x0b \\x01(\\r\\x12\\x14\\n\\x0cneedsRefresh\\x18\\x0c \\x01(\\x08\\x12\\x14\\n\\x0c\\x61liceBaseKey\\x18\\r \\x01(\\x0c\\x1a\\xb9\\x02\\n\\x05\\x43hain\\x12\\x18\\n\\x10senderRatchetKey\\x18\\x01 \\x01(\\x0c\\x12\\x1f\\n\\x17senderRatchetKeyPrivate\\x18\\x02 \\x01(\\x0c\\x12=\\n\\x08\\x63hainKey\\x18\\x03 \\x01(\\x0b\\x32+.textsecure.SessionStructure.Chain.ChainKey\\x12\\x42\\n\\x0bmessageKeys\\x18\\x04 \\x03(\\x0b\\x32-.textsecure.SessionStructure.Chain.MessageKey\\x1a&\\n\\x08\\x43hainKey\\x12\\r\\n\\x05index\\x18\\x01 \\x01(\\r\\x12\\x0b\\n\\x03key\\x18\\x02 \\x01(\\x0c\\x1aJ\\n\\nMessageKey\\x12\\r\\n\\x05index\\x18\\x01 \\x01(\\r\\x12\\x11\\n\\tcipherKey\\x18\\x02 \\x01(\\x0c\\x12\\x0e\\n\\x06macKey\\x18\\x03 \\x01(\\x0c\\x12\\n\\n\\x02iv\\x18\\x04 \\x01(\\x0c\\x1a\\xcd\\x01\\n\\x12PendingKeyExchange\\x12\\x10\\n\\x08sequence\\x18\\x01 \\x01(\\r\\x12\\x14\\n\\x0clocalBaseKey\\x18\\x02 \\x01(\\x0c\\x12\\x1b\\n\\x13localBaseKeyPrivate\\x18\\x03 \\x01(\\x0c\\x12\\x17\\n\\x0flocalRatchetKey\\x18\\x04 \\x01(\\x0c\\x12\\x1e\\n\\x16localRatchetKeyPrivate\\x18\\x05 \\x01(\\x0c\\x12\\x18\\n\\x10localIdentityKey\\x18\\x07 \\x01(\\x0c\\x12\\x1f\\n\\x17localIdentityKeyPrivate\\x18\\x08 \\x01(\\x0c\\x1aJ\\n\\rPendingPreKey\\x12\\x10\\n\\x08preKeyId\\x18\\x01 \\x01(\\r\\x12\\x16\\n\\x0esignedPreKeyId\\x18\\x03 \\x01(\\x05\\x12\\x0f\\n\\x07\\x62\\x61seKey\\x18\\x02 \\x01(\\x0c\\\"\\x7f\\n\\x0fRecordStructure\\x12\\x34\\n\\x0e\\x63urrentSession\\x18\\x01 \\x01(\\x0b\\x32\\x1c.textsecure.SessionStructure\\x12\\x36\\n\\x10previousSessions\\x18\\x02 \\x03(\\x0b\\x32\\x1c.textsecure.SessionStructure\\\"J\\n\\x15PreKeyRecordStructure\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\r\\x12\\x11\\n\\tpublicKey\\x18\\x02 \\x01(\\x0c\\x12\\x12\\n\\nprivateKey\\x18\\x03 \\x01(\\x0c\\\"v\\n\\x1bSignedPreKeyRecordStructure\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\r\\x12\\x11\\n\\tpublicKey\\x18\\x02 \\x01(\\x0c\\x12\\x12\\n\\nprivateKey\\x18\\x03 \\x01(\\x0c\\x12\\x11\\n\\tsignature\\x18\\x04 \\x01(\\x0c\\x12\\x11\\n\\ttimestamp\\x18\\x05 \\x01(\\x06\\\"A\\n\\x18IdentityKeyPairStructure\\x12\\x11\\n\\tpublicKey\\x18\\x01 \\x01(\\x0c\\x12\\x12\\n\\nprivateKey\\x18\\x02 \\x01(\\x0c\\\"\\xb8\\x03\\n\\x17SenderKeyStateStructure\\x12\\x13\\n\\x0bsenderKeyId\\x18\\x01 \\x01(\\r\\x12J\\n\\x0esenderChainKey\\x18\\x02 \\x01(\\x0b\\x32\\x32.textsecure.SenderKeyStateStructure.SenderChainKey\\x12N\\n\\x10senderSigningKey\\x18\\x03 \\x01(\\x0b\\x32\\x34.textsecure.SenderKeyStateStructure.SenderSigningKey\\x12O\\n\\x11senderMessageKeys\\x18\\x04 \\x03(\\x0b\\x32\\x34.textsecure.SenderKeyStateStructure.SenderMessageKey\\x1a\\x31\\n\\x0eSenderChainKey\\x12\\x11\\n\\titeration\\x18\\x01 \\x01(\\r\\x12\\x0c\\n\\x04seed\\x18\\x02 \\x01(\\x0c\\x1a\\x33\\n\\x10SenderMessageKey\\x12\\x11\\n\\titeration\\x18\\x01 \\x01(\\r\\x12\\x0c\\n\\x04seed\\x18\\x02 \\x01(\\x0c\\x1a\\x33\\n\\x10SenderSigningKey\\x12\\x0e\\n\\x06public\\x18\\x01 \\x01(\\x0c\\x12\\x0f\\n\\x07private\\x18\\x02 \\x01(\\x0c\\\"X\\n\\x18SenderKeyRecordStructure\\x12<\\n\\x0fsenderKeyStates\\x18\\x01 \\x03(\\x0b\\x32#.textsecure.SenderKeyStateStructureB4\\n#org.whispersystems.libaxolotl.stateB\\rStorageProtos')\n)\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n\n\n\n\n_SESSIONSTRUCTURE_CHAIN_CHAINKEY = _descriptor.Descriptor(\n  name='ChainKey',\n  full_name='textsecure.SessionStructure.Chain.ChainKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='index', full_name='textsecure.SessionStructure.Chain.ChainKey.index', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='key', full_name='textsecure.SessionStructure.Chain.ChainKey.key', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=752,\n  serialized_end=790,\n)\n\n_SESSIONSTRUCTURE_CHAIN_MESSAGEKEY = _descriptor.Descriptor(\n  name='MessageKey',\n  full_name='textsecure.SessionStructure.Chain.MessageKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='index', full_name='textsecure.SessionStructure.Chain.MessageKey.index', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='cipherKey', full_name='textsecure.SessionStructure.Chain.MessageKey.cipherKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='macKey', full_name='textsecure.SessionStructure.Chain.MessageKey.macKey', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='iv', full_name='textsecure.SessionStructure.Chain.MessageKey.iv', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=792,\n  serialized_end=866,\n)\n\n_SESSIONSTRUCTURE_CHAIN = _descriptor.Descriptor(\n  name='Chain',\n  full_name='textsecure.SessionStructure.Chain',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='senderRatchetKey', full_name='textsecure.SessionStructure.Chain.senderRatchetKey', index=0,\n      number=1, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='senderRatchetKeyPrivate', full_name='textsecure.SessionStructure.Chain.senderRatchetKeyPrivate', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='chainKey', full_name='textsecure.SessionStructure.Chain.chainKey', index=2,\n      number=3, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='messageKeys', full_name='textsecure.SessionStructure.Chain.messageKeys', index=3,\n      number=4, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[_SESSIONSTRUCTURE_CHAIN_CHAINKEY, _SESSIONSTRUCTURE_CHAIN_MESSAGEKEY, ],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=553,\n  serialized_end=866,\n)\n\n_SESSIONSTRUCTURE_PENDINGKEYEXCHANGE = _descriptor.Descriptor(\n  name='PendingKeyExchange',\n  full_name='textsecure.SessionStructure.PendingKeyExchange',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='sequence', full_name='textsecure.SessionStructure.PendingKeyExchange.sequence', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localBaseKey', full_name='textsecure.SessionStructure.PendingKeyExchange.localBaseKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localBaseKeyPrivate', full_name='textsecure.SessionStructure.PendingKeyExchange.localBaseKeyPrivate', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localRatchetKey', full_name='textsecure.SessionStructure.PendingKeyExchange.localRatchetKey', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localRatchetKeyPrivate', full_name='textsecure.SessionStructure.PendingKeyExchange.localRatchetKeyPrivate', index=4,\n      number=5, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localIdentityKey', full_name='textsecure.SessionStructure.PendingKeyExchange.localIdentityKey', index=5,\n      number=7, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localIdentityKeyPrivate', full_name='textsecure.SessionStructure.PendingKeyExchange.localIdentityKeyPrivate', index=6,\n      number=8, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=869,\n  serialized_end=1074,\n)\n\n_SESSIONSTRUCTURE_PENDINGPREKEY = _descriptor.Descriptor(\n  name='PendingPreKey',\n  full_name='textsecure.SessionStructure.PendingPreKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='preKeyId', full_name='textsecure.SessionStructure.PendingPreKey.preKeyId', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='signedPreKeyId', full_name='textsecure.SessionStructure.PendingPreKey.signedPreKeyId', index=1,\n      number=3, type=5, cpp_type=1, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='baseKey', full_name='textsecure.SessionStructure.PendingPreKey.baseKey', index=2,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1076,\n  serialized_end=1150,\n)\n\n_SESSIONSTRUCTURE = _descriptor.Descriptor(\n  name='SessionStructure',\n  full_name='textsecure.SessionStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='sessionVersion', full_name='textsecure.SessionStructure.sessionVersion', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localIdentityPublic', full_name='textsecure.SessionStructure.localIdentityPublic', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='remoteIdentityPublic', full_name='textsecure.SessionStructure.remoteIdentityPublic', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='rootKey', full_name='textsecure.SessionStructure.rootKey', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='previousCounter', full_name='textsecure.SessionStructure.previousCounter', index=4,\n      number=5, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='senderChain', full_name='textsecure.SessionStructure.senderChain', index=5,\n      number=6, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='receiverChains', full_name='textsecure.SessionStructure.receiverChains', index=6,\n      number=7, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='pendingKeyExchange', full_name='textsecure.SessionStructure.pendingKeyExchange', index=7,\n      number=8, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='pendingPreKey', full_name='textsecure.SessionStructure.pendingPreKey', index=8,\n      number=9, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='remoteRegistrationId', full_name='textsecure.SessionStructure.remoteRegistrationId', index=9,\n      number=10, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='localRegistrationId', full_name='textsecure.SessionStructure.localRegistrationId', index=10,\n      number=11, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='needsRefresh', full_name='textsecure.SessionStructure.needsRefresh', index=11,\n      number=12, type=8, cpp_type=7, label=1,\n      has_default_value=False, default_value=False,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='aliceBaseKey', full_name='textsecure.SessionStructure.aliceBaseKey', index=12,\n      number=13, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[_SESSIONSTRUCTURE_CHAIN, _SESSIONSTRUCTURE_PENDINGKEYEXCHANGE, _SESSIONSTRUCTURE_PENDINGPREKEY, ],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=43,\n  serialized_end=1150,\n)\n\n\n_RECORDSTRUCTURE = _descriptor.Descriptor(\n  name='RecordStructure',\n  full_name='textsecure.RecordStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='currentSession', full_name='textsecure.RecordStructure.currentSession', index=0,\n      number=1, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='previousSessions', full_name='textsecure.RecordStructure.previousSessions', index=1,\n      number=2, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1152,\n  serialized_end=1279,\n)\n\n\n_PREKEYRECORDSTRUCTURE = _descriptor.Descriptor(\n  name='PreKeyRecordStructure',\n  full_name='textsecure.PreKeyRecordStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='textsecure.PreKeyRecordStructure.id', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='publicKey', full_name='textsecure.PreKeyRecordStructure.publicKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='privateKey', full_name='textsecure.PreKeyRecordStructure.privateKey', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1281,\n  serialized_end=1355,\n)\n\n\n_SIGNEDPREKEYRECORDSTRUCTURE = _descriptor.Descriptor(\n  name='SignedPreKeyRecordStructure',\n  full_name='textsecure.SignedPreKeyRecordStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='textsecure.SignedPreKeyRecordStructure.id', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='publicKey', full_name='textsecure.SignedPreKeyRecordStructure.publicKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='privateKey', full_name='textsecure.SignedPreKeyRecordStructure.privateKey', index=2,\n      number=3, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='signature', full_name='textsecure.SignedPreKeyRecordStructure.signature', index=3,\n      number=4, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='timestamp', full_name='textsecure.SignedPreKeyRecordStructure.timestamp', index=4,\n      number=5, type=6, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1357,\n  serialized_end=1475,\n)\n\n\n_IDENTITYKEYPAIRSTRUCTURE = _descriptor.Descriptor(\n  name='IdentityKeyPairStructure',\n  full_name='textsecure.IdentityKeyPairStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='publicKey', full_name='textsecure.IdentityKeyPairStructure.publicKey', index=0,\n      number=1, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='privateKey', full_name='textsecure.IdentityKeyPairStructure.privateKey', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1477,\n  serialized_end=1542,\n)\n\n\n_SENDERKEYSTATESTRUCTURE_SENDERCHAINKEY = _descriptor.Descriptor(\n  name='SenderChainKey',\n  full_name='textsecure.SenderKeyStateStructure.SenderChainKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='iteration', full_name='textsecure.SenderKeyStateStructure.SenderChainKey.iteration', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='seed', full_name='textsecure.SenderKeyStateStructure.SenderChainKey.seed', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1830,\n  serialized_end=1879,\n)\n\n_SENDERKEYSTATESTRUCTURE_SENDERMESSAGEKEY = _descriptor.Descriptor(\n  name='SenderMessageKey',\n  full_name='textsecure.SenderKeyStateStructure.SenderMessageKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='iteration', full_name='textsecure.SenderKeyStateStructure.SenderMessageKey.iteration', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='seed', full_name='textsecure.SenderKeyStateStructure.SenderMessageKey.seed', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1881,\n  serialized_end=1932,\n)\n\n_SENDERKEYSTATESTRUCTURE_SENDERSIGNINGKEY = _descriptor.Descriptor(\n  name='SenderSigningKey',\n  full_name='textsecure.SenderKeyStateStructure.SenderSigningKey',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='public', full_name='textsecure.SenderKeyStateStructure.SenderSigningKey.public', index=0,\n      number=1, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='private', full_name='textsecure.SenderKeyStateStructure.SenderSigningKey.private', index=1,\n      number=2, type=12, cpp_type=9, label=1,\n      has_default_value=False, default_value=_b(\"\"),\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1934,\n  serialized_end=1985,\n)\n\n_SENDERKEYSTATESTRUCTURE = _descriptor.Descriptor(\n  name='SenderKeyStateStructure',\n  full_name='textsecure.SenderKeyStateStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='senderKeyId', full_name='textsecure.SenderKeyStateStructure.senderKeyId', index=0,\n      number=1, type=13, cpp_type=3, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='senderChainKey', full_name='textsecure.SenderKeyStateStructure.senderChainKey', index=1,\n      number=2, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='senderSigningKey', full_name='textsecure.SenderKeyStateStructure.senderSigningKey', index=2,\n      number=3, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='senderMessageKeys', full_name='textsecure.SenderKeyStateStructure.senderMessageKeys', index=3,\n      number=4, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[_SENDERKEYSTATESTRUCTURE_SENDERCHAINKEY, _SENDERKEYSTATESTRUCTURE_SENDERMESSAGEKEY, _SENDERKEYSTATESTRUCTURE_SENDERSIGNINGKEY, ],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1545,\n  serialized_end=1985,\n)\n\n\n_SENDERKEYRECORDSTRUCTURE = _descriptor.Descriptor(\n  name='SenderKeyRecordStructure',\n  full_name='textsecure.SenderKeyRecordStructure',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='senderKeyStates', full_name='textsecure.SenderKeyRecordStructure.senderKeyStates', index=0,\n      number=1, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1987,\n  serialized_end=2075,\n)\n\n_SESSIONSTRUCTURE_CHAIN_CHAINKEY.containing_type = _SESSIONSTRUCTURE_CHAIN\n_SESSIONSTRUCTURE_CHAIN_MESSAGEKEY.containing_type = _SESSIONSTRUCTURE_CHAIN\n_SESSIONSTRUCTURE_CHAIN.fields_by_name['chainKey'].message_type = _SESSIONSTRUCTURE_CHAIN_CHAINKEY\n_SESSIONSTRUCTURE_CHAIN.fields_by_name['messageKeys'].message_type = _SESSIONSTRUCTURE_CHAIN_MESSAGEKEY\n_SESSIONSTRUCTURE_CHAIN.containing_type = _SESSIONSTRUCTURE\n_SESSIONSTRUCTURE_PENDINGKEYEXCHANGE.containing_type = _SESSIONSTRUCTURE\n_SESSIONSTRUCTURE_PENDINGPREKEY.containing_type = _SESSIONSTRUCTURE\n_SESSIONSTRUCTURE.fields_by_name['senderChain'].message_type = _SESSIONSTRUCTURE_CHAIN\n_SESSIONSTRUCTURE.fields_by_name['receiverChains'].message_type = _SESSIONSTRUCTURE_CHAIN\n_SESSIONSTRUCTURE.fields_by_name['pendingKeyExchange'].message_type = _SESSIONSTRUCTURE_PENDINGKEYEXCHANGE\n_SESSIONSTRUCTURE.fields_by_name['pendingPreKey'].message_type = _SESSIONSTRUCTURE_PENDINGPREKEY\n_RECORDSTRUCTURE.fields_by_name['currentSession'].message_type = _SESSIONSTRUCTURE\n_RECORDSTRUCTURE.fields_by_name['previousSessions'].message_type = _SESSIONSTRUCTURE\n_SENDERKEYSTATESTRUCTURE_SENDERCHAINKEY.containing_type = _SENDERKEYSTATESTRUCTURE\n_SENDERKEYSTATESTRUCTURE_SENDERMESSAGEKEY.containing_type = _SENDERKEYSTATESTRUCTURE\n_SENDERKEYSTATESTRUCTURE_SENDERSIGNINGKEY.containing_type = _SENDERKEYSTATESTRUCTURE\n_SENDERKEYSTATESTRUCTURE.fields_by_name['senderChainKey'].message_type = _SENDERKEYSTATESTRUCTURE_SENDERCHAINKEY\n_SENDERKEYSTATESTRUCTURE.fields_by_name['senderSigningKey'].message_type = _SENDERKEYSTATESTRUCTURE_SENDERSIGNINGKEY\n_SENDERKEYSTATESTRUCTURE.fields_by_name['senderMessageKeys'].message_type = _SENDERKEYSTATESTRUCTURE_SENDERMESSAGEKEY\n_SENDERKEYRECORDSTRUCTURE.fields_by_name['senderKeyStates'].message_type = _SENDERKEYSTATESTRUCTURE\nDESCRIPTOR.message_types_by_name['SessionStructure'] = _SESSIONSTRUCTURE\nDESCRIPTOR.message_types_by_name['RecordStructure'] = _RECORDSTRUCTURE\nDESCRIPTOR.message_types_by_name['PreKeyRecordStructure'] = _PREKEYRECORDSTRUCTURE\nDESCRIPTOR.message_types_by_name['SignedPreKeyRecordStructure'] = _SIGNEDPREKEYRECORDSTRUCTURE\nDESCRIPTOR.message_types_by_name['IdentityKeyPairStructure'] = _IDENTITYKEYPAIRSTRUCTURE\nDESCRIPTOR.message_types_by_name['SenderKeyStateStructure'] = _SENDERKEYSTATESTRUCTURE\nDESCRIPTOR.message_types_by_name['SenderKeyRecordStructure'] = _SENDERKEYRECORDSTRUCTURE\n\nSessionStructure = _reflection.GeneratedProtocolMessageType('SessionStructure', (_message.Message,), dict(\n\n  Chain = _reflection.GeneratedProtocolMessageType('Chain', (_message.Message,), dict(\n\n    ChainKey = _reflection.GeneratedProtocolMessageType('ChainKey', (_message.Message,), dict(\n      DESCRIPTOR = _SESSIONSTRUCTURE_CHAIN_CHAINKEY,\n      __module__ = 'LocalStorageProtocol_pb2'\n      # @@protoc_insertion_point(class_scope:textsecure.SessionStructure.Chain.ChainKey)\n      ))\n    ,\n\n    MessageKey = _reflection.GeneratedProtocolMessageType('MessageKey', (_message.Message,), dict(\n      DESCRIPTOR = _SESSIONSTRUCTURE_CHAIN_MESSAGEKEY,\n      __module__ = 'LocalStorageProtocol_pb2'\n      # @@protoc_insertion_point(class_scope:textsecure.SessionStructure.Chain.MessageKey)\n      ))\n    ,\n    DESCRIPTOR = _SESSIONSTRUCTURE_CHAIN,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SessionStructure.Chain)\n    ))\n  ,\n\n  PendingKeyExchange = _reflection.GeneratedProtocolMessageType('PendingKeyExchange', (_message.Message,), dict(\n    DESCRIPTOR = _SESSIONSTRUCTURE_PENDINGKEYEXCHANGE,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SessionStructure.PendingKeyExchange)\n    ))\n  ,\n\n  PendingPreKey = _reflection.GeneratedProtocolMessageType('PendingPreKey', (_message.Message,), dict(\n    DESCRIPTOR = _SESSIONSTRUCTURE_PENDINGPREKEY,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SessionStructure.PendingPreKey)\n    ))\n  ,\n  DESCRIPTOR = _SESSIONSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SessionStructure)\n  ))\n_sym_db.RegisterMessage(SessionStructure)\n_sym_db.RegisterMessage(SessionStructure.Chain)\n_sym_db.RegisterMessage(SessionStructure.Chain.ChainKey)\n_sym_db.RegisterMessage(SessionStructure.Chain.MessageKey)\n_sym_db.RegisterMessage(SessionStructure.PendingKeyExchange)\n_sym_db.RegisterMessage(SessionStructure.PendingPreKey)\n\nRecordStructure = _reflection.GeneratedProtocolMessageType('RecordStructure', (_message.Message,), dict(\n  DESCRIPTOR = _RECORDSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.RecordStructure)\n  ))\n_sym_db.RegisterMessage(RecordStructure)\n\nPreKeyRecordStructure = _reflection.GeneratedProtocolMessageType('PreKeyRecordStructure', (_message.Message,), dict(\n  DESCRIPTOR = _PREKEYRECORDSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.PreKeyRecordStructure)\n  ))\n_sym_db.RegisterMessage(PreKeyRecordStructure)\n\nSignedPreKeyRecordStructure = _reflection.GeneratedProtocolMessageType('SignedPreKeyRecordStructure', (_message.Message,), dict(\n  DESCRIPTOR = _SIGNEDPREKEYRECORDSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SignedPreKeyRecordStructure)\n  ))\n_sym_db.RegisterMessage(SignedPreKeyRecordStructure)\n\nIdentityKeyPairStructure = _reflection.GeneratedProtocolMessageType('IdentityKeyPairStructure', (_message.Message,), dict(\n  DESCRIPTOR = _IDENTITYKEYPAIRSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.IdentityKeyPairStructure)\n  ))\n_sym_db.RegisterMessage(IdentityKeyPairStructure)\n\nSenderKeyStateStructure = _reflection.GeneratedProtocolMessageType('SenderKeyStateStructure', (_message.Message,), dict(\n\n  SenderChainKey = _reflection.GeneratedProtocolMessageType('SenderChainKey', (_message.Message,), dict(\n    DESCRIPTOR = _SENDERKEYSTATESTRUCTURE_SENDERCHAINKEY,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SenderKeyStateStructure.SenderChainKey)\n    ))\n  ,\n\n  SenderMessageKey = _reflection.GeneratedProtocolMessageType('SenderMessageKey', (_message.Message,), dict(\n    DESCRIPTOR = _SENDERKEYSTATESTRUCTURE_SENDERMESSAGEKEY,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SenderKeyStateStructure.SenderMessageKey)\n    ))\n  ,\n\n  SenderSigningKey = _reflection.GeneratedProtocolMessageType('SenderSigningKey', (_message.Message,), dict(\n    DESCRIPTOR = _SENDERKEYSTATESTRUCTURE_SENDERSIGNINGKEY,\n    __module__ = 'LocalStorageProtocol_pb2'\n    # @@protoc_insertion_point(class_scope:textsecure.SenderKeyStateStructure.SenderSigningKey)\n    ))\n  ,\n  DESCRIPTOR = _SENDERKEYSTATESTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SenderKeyStateStructure)\n  ))\n_sym_db.RegisterMessage(SenderKeyStateStructure)\n_sym_db.RegisterMessage(SenderKeyStateStructure.SenderChainKey)\n_sym_db.RegisterMessage(SenderKeyStateStructure.SenderMessageKey)\n_sym_db.RegisterMessage(SenderKeyStateStructure.SenderSigningKey)\n\nSenderKeyRecordStructure = _reflection.GeneratedProtocolMessageType('SenderKeyRecordStructure', (_message.Message,), dict(\n  DESCRIPTOR = _SENDERKEYRECORDSTRUCTURE,\n  __module__ = 'LocalStorageProtocol_pb2'\n  # @@protoc_insertion_point(class_scope:textsecure.SenderKeyRecordStructure)\n  ))\n_sym_db.RegisterMessage(SenderKeyRecordStructure)\n\n\nDESCRIPTOR.has_options = True\nDESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\\n#org.whispersystems.libaxolotl.stateB\\rStorageProtos'))\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "axolotl/statekeyexchangeexception.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass StaleKeyExchangeException(Exception):\n    pass\n"
  },
  {
    "path": "axolotl/tests/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/tests/groups/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/tests/groups/inmemorysenderkeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ...groups.state.senderkeystore import SenderKeyStore\nfrom ...groups.state.senderkeyrecord import SenderKeyRecord\n\n\nclass InMemorySenderKeyStore(SenderKeyStore):\n    def __init__(self):\n        self.store = {}\n\n    def storeSenderKey(self, senderKeyName, senderKeyRecord):\n        self.store[senderKeyName] = senderKeyRecord\n\n    def loadSenderKey(self, senderKeyName):\n        if senderKeyName in self.store:\n            return SenderKeyRecord(serialized=self.store[senderKeyName].serialize())\n\n        return SenderKeyRecord()\n"
  },
  {
    "path": "axolotl/tests/groups/test_groupcipher.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom .inmemorysenderkeystore import InMemorySenderKeyStore\nfrom ...groups.groupsessionbuilder import GroupSessionBuilder\nfrom ...util.keyhelper import KeyHelper\nfrom ...groups.groupcipher import GroupCipher\nfrom ...duplicatemessagexception import DuplicateMessageException\nfrom ...nosessionexception import NoSessionException\nfrom ...groups.senderkeyname import SenderKeyName\nfrom ...axolotladdress import AxolotlAddress\nfrom ...protocol.senderkeydistributionmessage import SenderKeyDistributionMessage\n\nSENDER_ADDRESS = AxolotlAddress(\"+14150001111\", 1)\nGROUP_SENDER   = SenderKeyName(\"nihilist history reading group\", SENDER_ADDRESS);\n\n\n\nclass GroupCipherTest(unittest.TestCase):\n\n    def test_noSession(self):\n        aliceStore = InMemorySenderKeyStore();\n        bobStore = InMemorySenderKeyStore();\n\n        aliceSessionBuilder = GroupSessionBuilder(aliceStore)\n        bobSessionBuilder   = GroupSessionBuilder(bobStore)\n\n        aliceGroupCipher = GroupCipher(aliceStore, GROUP_SENDER)\n        bobGroupCipher = GroupCipher(bobStore, GROUP_SENDER);\n\n        sentAliceDistributionMessage = aliceSessionBuilder.create(GROUP_SENDER);\n        receivedAliceDistributionMessage = SenderKeyDistributionMessage(serialized = sentAliceDistributionMessage.serialize());\n\n        ciphertextFromAlice = aliceGroupCipher.encrypt(b\"smert ze smert\");\n\n        try:\n            plaintextFromAlice = bobGroupCipher.decrypt(ciphertextFromAlice);\n            raise AssertionError(\"Should be no session!\");\n        except NoSessionException as e:\n            pass\n    def test_basicEncryptDecrypt(self):\n        aliceStore = InMemorySenderKeyStore();\n        bobStore = InMemorySenderKeyStore();\n\n        aliceSessionBuilder = GroupSessionBuilder(aliceStore)\n        bobSessionBuilder = GroupSessionBuilder(bobStore)\n\n        aliceGroupCipher = GroupCipher(aliceStore, GROUP_SENDER)\n        bobGroupCipher = GroupCipher(bobStore, GROUP_SENDER);\n\n        sentAliceDistributionMessage = aliceSessionBuilder.create(GROUP_SENDER);\n        receivedAliceDistributionMessage = SenderKeyDistributionMessage(serialized = sentAliceDistributionMessage.serialize());\n\n        bobSessionBuilder.process(GROUP_SENDER, receivedAliceDistributionMessage)\n\n        ciphertextFromAlice = aliceGroupCipher.encrypt(b\"smert ze smert\")\n        plaintextFromAlice = bobGroupCipher.decrypt(ciphertextFromAlice)\n\n        self.assertEqual(plaintextFromAlice, b\"smert ze smert\")\n\n    def test_basicRatchet(self):\n        aliceStore = InMemorySenderKeyStore()\n        bobStore = InMemorySenderKeyStore()\n\n        aliceSessionBuilder = GroupSessionBuilder(aliceStore)\n        bobSessionBuilder = GroupSessionBuilder(bobStore)\n\n        aliceGroupCipher = GroupCipher(aliceStore, \"groupWithBobInIt\")\n        bobGroupCipher   = GroupCipher(bobStore, \"groupWithBobInIt::aliceUserName\")\n\n        aliceGroupCipher = GroupCipher(aliceStore, GROUP_SENDER)\n        bobGroupCipher   = GroupCipher(bobStore, GROUP_SENDER);\n\n        sentAliceDistributionMessage = aliceSessionBuilder.create(GROUP_SENDER);\n        receivedAliceDistributionMessage = SenderKeyDistributionMessage(serialized = sentAliceDistributionMessage.serialize());\n\n        bobSessionBuilder.process(GROUP_SENDER, receivedAliceDistributionMessage)\n\n        ciphertextFromAlice  = aliceGroupCipher.encrypt(b\"smert ze smert\")\n        ciphertextFromAlice2 = aliceGroupCipher.encrypt(b\"smert ze smert2\")\n        ciphertextFromAlice3 = aliceGroupCipher.encrypt(b\"smert ze smert3\")\n\n        plaintextFromAlice = bobGroupCipher.decrypt(ciphertextFromAlice)\n\n        try:\n            bobGroupCipher.decrypt(ciphertextFromAlice)\n            raise AssertionError(\"Should have ratcheted forward!\")\n        except DuplicateMessageException as dme:\n            # good\n            pass\n\n        plaintextFromAlice2 = bobGroupCipher.decrypt(ciphertextFromAlice2)\n        plaintextFromAlice3 = bobGroupCipher.decrypt(ciphertextFromAlice3)\n\n        self.assertEqual(plaintextFromAlice, b\"smert ze smert\")\n        self.assertEqual(plaintextFromAlice2, b\"smert ze smert2\")\n        self.assertEqual(plaintextFromAlice3, b\"smert ze smert3\")\n\n\n    def test_outOfOrder(self):\n        aliceStore = InMemorySenderKeyStore();\n        bobStore   = InMemorySenderKeyStore();\n\n        aliceSessionBuilder = GroupSessionBuilder(aliceStore)\n        bobSessionBuilder   = GroupSessionBuilder(bobStore)\n\n        aliceGroupCipher = GroupCipher(aliceStore, \"groupWithBobInIt\")\n        bobGroupCipher   = GroupCipher(bobStore, \"groupWithBobInIt::aliceUserName\")\n\n        aliceGroupCipher = GroupCipher(aliceStore, GROUP_SENDER)\n        bobGroupCipher = GroupCipher(bobStore, GROUP_SENDER);\n\n        sentAliceDistributionMessage = aliceSessionBuilder.create(GROUP_SENDER);\n        receivedAliceDistributionMessage = SenderKeyDistributionMessage(serialized = sentAliceDistributionMessage.serialize());\n\n        bobSessionBuilder.process(GROUP_SENDER, receivedAliceDistributionMessage)\n\n        ciphertexts = []\n        for i in range(0, 100):\n            ciphertexts.append(aliceGroupCipher.encrypt(b\"up the punks\"))\n        while len(ciphertexts) > 0:\n            index = KeyHelper.getRandomSequence(2147483647) % len(ciphertexts)\n            ciphertext = ciphertexts.pop(index)\n            plaintext = bobGroupCipher.decrypt(ciphertext)\n            self.assertEqual(plaintext, b\"up the punks\")\n\n    def test_encryptNoSession(self):\n\n        aliceStore = InMemorySenderKeyStore()\n        aliceGroupCipher = GroupCipher(aliceStore, \"groupWithBobInIt\")\n        try:\n            aliceGroupCipher.encrypt(b\"up the punks\")\n            raise AssertionError(\"Should have failed!\")\n        except NoSessionException as nse:\n            # good\n            pass"
  },
  {
    "path": "axolotl/tests/inmemoryaxolotlstore.py",
    "content": "# -*- coding: utf8 -*-\n\nfrom ..state.axolotlstore import AxolotlStore\nfrom .inmemoryidentitykeystore import InMemoryIdentityKeyStore\nfrom .inmemoryprekeystore import InMemoryPreKeyStore\nfrom .inmemorysessionstore import InMemorySessionStore\nfrom .inmemorysignedprekeystore import InMemorySignedPreKeyStore\n\n\nclass InMemoryAxolotlStore(AxolotlStore):\n    def __init__(self):\n        self.identityKeyStore = InMemoryIdentityKeyStore()\n        self.preKeyStore = InMemoryPreKeyStore()\n        self.signedPreKeyStore = InMemorySignedPreKeyStore()\n        self.sessionStore = InMemorySessionStore()\n\n    def getIdentityKeyPair(self):\n        return self.identityKeyStore.getIdentityKeyPair()\n\n    def getLocalRegistrationId(self):\n        return self.identityKeyStore.getLocalRegistrationId()\n\n    def saveIdentity(self, recepientId, identityKey):\n        self.identityKeyStore.saveIdentity(recepientId, identityKey)\n\n    def isTrustedIdentity(self, recepientId, identityKey):\n        return self.identityKeyStore.isTrustedIdentity(recepientId, identityKey)\n\n    def loadPreKey(self, preKeyId):\n        return self.preKeyStore.loadPreKey(preKeyId)\n\n    def storePreKey(self, preKeyId, preKeyRecord):\n        self.preKeyStore.storePreKey(preKeyId, preKeyRecord)\n\n    def containsPreKey(self, preKeyId):\n        return self.preKeyStore.containsPreKey(preKeyId)\n\n    def removePreKey(self, preKeyId):\n        self.preKeyStore.removePreKey(preKeyId)\n\n    def loadSession(self, recepientId, deviceId):\n        return self.sessionStore.loadSession(recepientId, deviceId)\n\n    def getSubDeviceSessions(self, recepientId):\n        return self.sessionStore.getSubDeviceSessions(recepientId)\n\n    def storeSession(self, recepientId, deviceId, sessionRecord):\n        self.sessionStore.storeSession(recepientId, deviceId, sessionRecord)\n\n    def containsSession(self, recepientId, deviceId):\n        return self.sessionStore.containsSession(recepientId, deviceId)\n\n    def deleteSession(self, recepientId, deviceId):\n        self.sessionStore.deleteSession(recepientId, deviceId)\n\n    def deleteAllSessions(self, recepientId):\n        self.sessionStore.deleteAllSessions(recepientId)\n\n    def loadSignedPreKey(self, signedPreKeyId):\n        return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId)\n\n    def loadSignedPreKeys(self):\n        return self.signedPreKeyStore.loadSignedPreKeys()\n\n    def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):\n        self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId, signedPreKeyRecord)\n\n    def containsSignedPreKey(self, signedPreKeyId):\n        return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId)\n\n    def removeSignedPreKey(self, signedPreKeyId):\n        return self.signedPreKeyStore.containsSignedPreKey()\n"
  },
  {
    "path": "axolotl/tests/inmemoryidentitykeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..state.identitykeystore import IdentityKeyStore\nfrom ..ecc.curve import Curve\nfrom ..identitykey import IdentityKey\nfrom ..util.keyhelper import KeyHelper\nfrom ..identitykeypair import IdentityKeyPair\n\n\nclass InMemoryIdentityKeyStore(IdentityKeyStore):\n    def __init__(self):\n        self.trustedKeys = {}\n        identityKeyPairKeys = Curve.generateKeyPair()\n        self.identityKeyPair = IdentityKeyPair(IdentityKey(identityKeyPairKeys.getPublicKey()),\n                                               identityKeyPairKeys.getPrivateKey())\n        self.localRegistrationId = KeyHelper.generateRegistrationId()\n\n    def getIdentityKeyPair(self):\n        return self.identityKeyPair\n\n    def getLocalRegistrationId(self):\n        return self.localRegistrationId\n\n    def saveIdentity(self, recepientId, identityKey):\n        self.trustedKeys[recepientId] = identityKey\n\n    def isTrustedIdentity(self, recepientId, identityKey):\n        if recepientId not in self.trustedKeys:\n            return True\n        return self.trustedKeys[recepientId] == identityKey\n"
  },
  {
    "path": "axolotl/tests/inmemoryprekeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..state.prekeystore import PreKeyStore\nfrom ..state.prekeyrecord import PreKeyRecord\nfrom ..invalidkeyidexception import InvalidKeyIdException\n\n\nclass InMemoryPreKeyStore(PreKeyStore):\n    def __init__(self):\n        self.store = {}\n\n    def loadPreKey(self, preKeyId):\n        if preKeyId not in self.store:\n            raise InvalidKeyIdException(\"No such prekeyRecord!\")\n\n        return PreKeyRecord(serialized=self.store[preKeyId])\n\n    def storePreKey(self, preKeyId, preKeyRecord):\n        self.store[preKeyId] = preKeyRecord.serialize()\n\n    def containsPreKey(self, preKeyId):\n        return preKeyId in self.store\n\n    def removePreKey(self, preKeyId):\n        if preKeyId in self.store:\n            del self.store[preKeyId]\n"
  },
  {
    "path": "axolotl/tests/inmemorysessionstore.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..state.sessionstore import SessionStore\nfrom ..state.sessionrecord import SessionRecord\n\n\nclass InMemorySessionStore(SessionStore):\n    def __init__(self):\n        self.sessions = {}\n\n    def loadSession(self, recepientId, deviceId):\n        if self.containsSession(recepientId, deviceId):\n            return SessionRecord(serialized=self.sessions[(recepientId, deviceId)])\n        else:\n            return SessionRecord()\n\n    def getSubDeviceSessions(self, recepientId):\n        deviceIds = []\n        for k in self.sessions.keys():\n            if k[0] == recepientId:\n                deviceIds.append(k[1])\n\n        return deviceIds\n\n    def storeSession(self, recepientId, deviceId, sessionRecord):\n        self.sessions[(recepientId, deviceId)] = sessionRecord.serialize()\n\n    def containsSession(self, recepientId, deviceId):\n        return (recepientId, deviceId) in self.sessions\n\n    def deleteSession(self, recepientId, deviceId):\n        del self.sessions[(recepientId, deviceId)]\n\n    def deleteAllSessions(self, recepientId):\n        for k in self.sessions.keys():\n            if k[0] == recepientId:\n                del self.sessions[k]\n"
  },
  {
    "path": "axolotl/tests/inmemorysignedprekeystore.py",
    "content": "# -*- coding: utf-8 -*-\n\nfrom ..state.signedprekeystore import SignedPreKeyStore\nfrom ..state.signedprekeyrecord import SignedPreKeyRecord\nfrom ..invalidkeyidexception import InvalidKeyIdException\n\n\nclass InMemorySignedPreKeyStore(SignedPreKeyStore):\n    def __init__(self):\n        self.store = {}\n\n    def loadSignedPreKey(self, signedPreKeyId):\n        if signedPreKeyId not in self.store:\n            raise InvalidKeyIdException(\"No such signedprekeyrecord! %s \" % signedPreKeyId)\n\n        return SignedPreKeyRecord(serialized=self.store[signedPreKeyId])\n\n    def loadSignedPreKeys(self):\n        results = []\n        for serialized in self.store.values():\n            results.append(SignedPreKeyRecord(serialized=serialized))\n\n        return results\n\n    def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):\n        self.store[signedPreKeyId] = signedPreKeyRecord.serialize()\n\n    def containsSignedPreKey(self, signedPreKeyId):\n        return signedPreKeyId in self.store\n\n    def removeSignedPreKey(self, signedPreKeyId):\n        del self.store[signedPreKeyId]\n"
  },
  {
    "path": "axolotl/tests/kdf/__init__.py",
    "content": "# -*- cosing: utf-8 -*-\n\n__author__ = 'tarek'\n"
  },
  {
    "path": "axolotl/tests/kdf/test_hkdf.py",
    "content": "# -*- coding ;utf-8 -*-\n\nimport unittest\n\nfrom ...kdf.hkdf import HKDF\n\n\nclass HKDFTest(unittest.TestCase):\n    def test_vectorV3(self):\n        ikm = bytearray([0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,\n                         0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b])\n\n        salt = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c])\n\n        info = bytearray([0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9])\n\n        okm = bytearray([0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f,\n                         0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4,\n                         0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65])\n\n        actualOutput = HKDF.createFor(3).deriveSecrets(ikm, info, 42, salt=salt)\n        self.assertEqual(okm, actualOutput)\n\n    def test_vectorLongV3(self):\n        ikm = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,\n                         0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,\n                         0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,\n                         0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,\n                         0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,\n                         0x4b, 0x4c, 0x4d, 0x4e, 0x4f])\n\n        salt = bytearray([0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,\n                          0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d,\n                          0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c,\n                          0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,\n                          0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,\n                          0xab, 0xac, 0xad, 0xae, 0xaf])\n\n        info = bytearray([0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe,\n                          0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd,\n                          0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc,\n                          0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,\n                          0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa,\n                          0xfb, 0xfc, 0xfd, 0xfe, 0xff])\n\n        okm = bytearray([0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49,\n                         0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf,\n                         0xa9, 0x7c, 0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e,\n                         0x59, 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9,\n                         0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, 0xc1, 0x4c, 0x01,\n                         0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87])\n\n        actualOutput = HKDF.createFor(3).deriveSecrets(ikm, info, 82, salt=salt)\n        self.assertEqual(okm, actualOutput)\n\n    def test_vectorV3_(self):\n        ikm = bytearray([0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,\n                         0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b])\n\n        salt = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c])\n\n        info = bytearray([0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9])\n\n        okm = bytearray([0x6e, 0xc2, 0x55, 0x6d, 0x5d, 0x7b, 0x1d, 0x81, 0xde, 0xe4, 0x22, 0x2a, 0xd7, 0x48, 0x36,\n                         0x95, 0xdd, 0xc9, 0x8f, 0x4f, 0x5f, 0xab, 0xc0, 0xe0, 0x20, 0x5d, 0xc2, 0xef, 0x87, 0x52,\n                         0xd4, 0x1e, 0x04, 0xe2, 0xe2, 0x11, 0x01, 0xc6, 0x8f, 0xf0, 0x93, 0x94, 0xb8, 0xad, 0x0b,\n                         0xdc, 0xb9, 0x60, 0x9c, 0xd4, 0xee, 0x82, 0xac, 0x13, 0x19, 0x9b, 0x4a, 0xa9, 0xfd, 0xa8,\n                         0x99, 0xda, 0xeb, 0xec])\n\n        actualOutput = HKDF.createFor(2).deriveSecrets(ikm, info, 64, salt=salt)\n        self.assertEqual(okm, actualOutput)\n"
  },
  {
    "path": "axolotl/tests/ratchet/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n__author__ = 'tarek'\n"
  },
  {
    "path": "axolotl/tests/ratchet/test_chainkey.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ...ratchet.chainkey import ChainKey\nfrom ...kdf.hkdf import HKDF\n\n\nclass ChainKeyTest(unittest.TestCase):\n    def test_chainKeyDerivationV2(self):\n        seed = bytearray([0x8a, 0xb7, 0x2d, 0x6f, 0x4c, 0xc5, 0xac, 0x0d, 0x38, 0x7e, 0xaf, 0x46, 0x33, 0x78, 0xdd,\n                          0xb2, 0x8e, 0xdd, 0x07, 0x38, 0x5b, 0x1c, 0xb0, 0x12, 0x50, 0xc7, 0x15, 0x98, 0x2e, 0x7a,\n                          0xd4, 0x8f])\n\n        messageKey = bytearray([0x02, 0xa9, 0xaa, 0x6c, 0x7d, 0xbd, 0x64, 0xf9, 0xd3, 0xaa, 0x92, 0xf9, 0x2a, 0x27,\n                                0x7b, 0xf5, 0x46, 0x09, 0xda, 0xdf, 0x0b, 0x00, 0x82, 0x8a, 0xcf, 0xc6, 0x1e, 0x3c,\n                                0x72, 0x4b, 0x84, 0xa7])\n\n        macKey = bytearray([0xbf, 0xbe, 0x5e, 0xfb, 0x60, 0x30, 0x30, 0x52, 0x67, 0x42, 0xe3, 0xee, 0x89, 0xc7,\n                            0x02, 0x4e, 0x88, 0x4e, 0x44, 0x0f, 0x1f, 0xf3, 0x76, 0xbb, 0x23, 0x17, 0xb2, 0xd6,\n                            0x4d, 0xeb, 0x7c, 0x83])\n\n        nextChainKey = bytearray([0x28, 0xe8, 0xf8, 0xfe, 0xe5, 0x4b, 0x80, 0x1e, 0xef, 0x7c, 0x5c, 0xfb, 0x2f,\n                                  0x17, 0xf3, 0x2c, 0x7b, 0x33, 0x44, 0x85, 0xbb, 0xb7, 0x0f, 0xac, 0x6e, 0xc1,\n                                  0x03, 0x42, 0xa2, 0x46, 0xd1, 0x5d])\n\n        chainKey = ChainKey(HKDF.createFor(2), seed, 0)\n        self.assertEqual(chainKey.getKey(), seed)\n        self.assertEqual(chainKey.getMessageKeys().getCipherKey(), messageKey)\n        self.assertEqual(chainKey.getMessageKeys().getMacKey(), macKey)\n        self.assertEqual(chainKey.getNextChainKey().getKey(), nextChainKey)\n        self.assertEqual(chainKey.getIndex(), 0)\n        self.assertEqual(chainKey.getMessageKeys().getCounter(), 0)\n        self.assertEqual(chainKey.getNextChainKey().getIndex(), 1)\n        self.assertEqual(chainKey.getNextChainKey().getMessageKeys().getCounter(), 1)\n"
  },
  {
    "path": "axolotl/tests/ratchet/test_ratchetingsession.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ...identitykey import IdentityKey\nfrom ...identitykeypair import IdentityKeyPair\nfrom ...ecc.curve import Curve\nfrom ...ecc.eckeypair import ECKeyPair\nfrom ...ratchet.bobaxolotlparamaters import BobAxolotlParameters\nfrom ...state.sessionstate import SessionState\nfrom ...ratchet.ratchetingsession import RatchetingSession\n\n\nclass RatchetingSessionTest(unittest.TestCase):\n    def test_ratchetingSessionAsBob(self):\n        bobPublic = bytearray([0x05, 0x2c, 0xb4, 0x97, 0x76, 0xb8, 0x77, 0x02, 0x05, 0x74, 0x5a, 0x3a, 0x6e, 0x24,\n                               0xf5, 0x79, 0xcd, 0xb4, 0xba, 0x7a, 0x89, 0x04, 0x10, 0x05, 0x92, 0x8e, 0xbb, 0xad,\n                               0xc9, 0xc0, 0x5a, 0xd4, 0x58])\n\n        bobPrivate = bytearray([0xa1, 0xca, 0xb4, 0x8f, 0x7c, 0x89, 0x3f, 0xaf, 0xa9, 0x88, 0x0a, 0x28, 0xc3, 0xb4,\n                                0x99, 0x9d, 0x28, 0xd6, 0x32, 0x95, 0x62, 0xd2, 0x7a, 0x4e, 0xa4, 0xe2, 0x2e, 0x9f,\n                                0xf1, 0xbd, 0xd6, 0x5a])\n\n        bobIdentityPublic = bytearray([0x05, 0xf1, 0xf4, 0x38, 0x74, 0xf6, 0x96, 0x69, 0x56, 0xc2, 0xdd, 0x47,\n                                       0x3f, 0x8f, 0xa1, 0x5a, 0xde, 0xb7, 0x1d, 0x1c, 0xb9, 0x91, 0xb2, 0x34,\n                                       0x16, 0x92, 0x32, 0x4c, 0xef, 0xb1, 0xc5, 0xe6, 0x26])\n\n        bobIdentityPrivate = bytearray([0x48, 0x75, 0xcc, 0x69, 0xdd, 0xf8, 0xea, 0x07, 0x19, 0xec, 0x94, 0x7d,\n                                        0x61, 0x08, 0x11, 0x35, 0x86, 0x8d, 0x5f, 0xd8, 0x01, 0xf0, 0x2c, 0x02,\n                                        0x25, 0xe5, 0x16, 0xdf, 0x21, 0x56, 0x60, 0x5e])\n\n        aliceBasePublic = bytearray([0x05, 0x47, 0x2d, 0x1f, 0xb1, 0xa9, 0x86, 0x2c, 0x3a, 0xf6, 0xbe, 0xac, 0xa8,\n                                     0x92, 0x02, 0x77, 0xe2, 0xb2, 0x6f, 0x4a, 0x79, 0x21, 0x3e, 0xc7, 0xc9, 0x06,\n                                     0xae, 0xb3, 0x5e, 0x03, 0xcf, 0x89, 0x50])\n\n        aliceEphemeralPublic = bytearray([0x05, 0x6c, 0x3e, 0x0d, 0x1f, 0x52, 0x02, 0x83, 0xef, 0xcc, 0x55, 0xfc,\n                                          0xa5, 0xe6, 0x70, 0x75, 0xb9, 0x04, 0x00, 0x7f, 0x18, 0x81, 0xd1, 0x51,\n                                          0xaf, 0x76, 0xdf, 0x18, 0xc5, 0x1d, 0x29, 0xd3, 0x4b])\n\n        aliceIdentityPublic = bytearray([0x05, 0xb4, 0xa8, 0x45, 0x56, 0x60, 0xad, 0xa6, 0x5b, 0x40, 0x10, 0x07,\n                                         0xf6, 0x15, 0xe6, 0x54, 0x04, 0x17, 0x46, 0x43, 0x2e, 0x33, 0x39, 0xc6,\n                                         0x87, 0x51, 0x49, 0xbc, 0xee, 0xfc, 0xb4, 0x2b, 0x4a])\n\n        bobSignedPreKeyPublic = bytearray([\n            0x05, 0xac, 0x24, 0x8a, 0x8f,\n            0x26, 0x3b, 0xe6, 0x86, 0x35,\n            0x76, 0xeb, 0x03, 0x62, 0xe2,\n            0x8c, 0x82, 0x8f, 0x01, 0x07,\n            0xa3, 0x37, 0x9d, 0x34, 0xba,\n            0xb1, 0x58, 0x6b, 0xf8, 0xc7,\n            0x70, 0xcd, 0x67\n        ])\n        bobSignedPreKeyPrivate = bytearray([\n            0x58, 0x39, 0x00, 0x13, 0x1f,\n            0xb7, 0x27, 0x99, 0x8b, 0x78,\n            0x03, 0xfe, 0x6a, 0xc2, 0x2c,\n            0xc5, 0x91, 0xf3, 0x42, 0xe4,\n            0xe4, 0x2a, 0x8c, 0x8d, 0x5d,\n            0x78, 0x19, 0x42, 0x09, 0xb8,\n            0xd2, 0x53])\n\n        senderChain = bytearray([\n            0x97, 0x97, 0xca, 0xca, 0x53,\n            0xc9, 0x89, 0xbb, 0xe2, 0x29,\n            0xa4, 0x0c, 0xa7, 0x72, 0x70,\n            0x10, 0xeb, 0x26, 0x04, 0xfc,\n            0x14, 0x94, 0x5d, 0x77, 0x95,\n            0x8a, 0x0a, 0xed, 0xa0, 0x88,\n            0xb4, 0x4d])\n\n        bobIdentityKeyPublic = IdentityKey(bobIdentityPublic, 0)\n        bobIdentityKeyPrivate = Curve.decodePrivatePoint(bobIdentityPrivate)\n        bobIdentityKey = IdentityKeyPair(bobIdentityKeyPublic, bobIdentityKeyPrivate)\n        bobEphemeralPublicKey = Curve.decodePoint(bobPublic, 0)\n        bobEphemeralPrivateKey = Curve.decodePrivatePoint(bobPrivate)\n        bobEphemeralKey = ECKeyPair(bobEphemeralPublicKey, bobEphemeralPrivateKey)\n        bobBaseKey = bobEphemeralKey\n        bobSignedPreKey = ECKeyPair(Curve.decodePoint(bobSignedPreKeyPublic, 0),\n                                    Curve.decodePrivatePoint(bobSignedPreKeyPrivate))\n\n\n        aliceBasePublicKey = Curve.decodePoint(aliceBasePublic, 0)\n        aliceEphemeralPublicKey = Curve.decodePoint(aliceEphemeralPublic, 0)\n        aliceIdentityPublicKey = IdentityKey(aliceIdentityPublic, 0)\n\n        parameters = BobAxolotlParameters.newBuilder() \\\n            .setOurIdentityKey(bobIdentityKey) \\\n            .setOurSignedPreKey(bobSignedPreKey) \\\n            .setOurRatchetKey(bobEphemeralKey) \\\n            .setOurOneTimePreKey(None) \\\n            .setTheirIdentityKey(aliceIdentityPublicKey) \\\n            .setTheirBaseKey(aliceBasePublicKey) \\\n            .create()\n\n        session = SessionState()\n\n        RatchetingSession.initializeSessionAsBob(session, parameters)\n        self.assertEqual(session.getLocalIdentityKey(), bobIdentityKey.getPublicKey())\n        self.assertEqual(session.getRemoteIdentityKey(), aliceIdentityPublicKey)\n        self.assertEqual(session.getSenderChainKey().getKey(), senderChain)\n"
  },
  {
    "path": "axolotl/tests/ratchet/test_rootkey.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ...ecc.curve import Curve\nfrom ...ecc.eckeypair import ECKeyPair\nfrom ...ratchet.rootkey import RootKey\nfrom ...kdf.hkdf import HKDF\n\n\nclass RootKeyTest(unittest.TestCase):\n    def test_rootKeyDerivationV2(self):\n        rootKeySeed = bytearray([0x7b, 0xa6, 0xde, 0xbc, 0x2b, 0xc1, 0xbb, 0xf9, 0x1a, 0xbb, 0xc1, 0x36, 0x74,\n                                 0x04, 0x17, 0x6c, 0xa6, 0x23, 0x09, 0x5b, 0x7e, 0xc6, 0x6b, 0x45, 0xf6, 0x02,\n                                 0xd9, 0x35, 0x38, 0x94, 0x2d, 0xcc])\n\n        alicePublic = bytearray([0x05, 0xee, 0x4f, 0xa6, 0xcd, 0xc0, 0x30, 0xdf, 0x49, 0xec, 0xd0, 0xba, 0x6c,\n                                 0xfc, 0xff, 0xb2, 0x33, 0xd3, 0x65, 0xa2, 0x7f, 0xad, 0xbe, 0xff, 0x77, 0xe9,\n                                 0x63, 0xfc, 0xb1, 0x62, 0x22, 0xe1, 0x3a])\n\n        alicePrivate = bytearray([0x21, 0x68, 0x22, 0xec, 0x67, 0xeb, 0x38, 0x04, 0x9e, 0xba, 0xe7, 0xb9, 0x39,\n                                  0xba, 0xea, 0xeb, 0xb1, 0x51, 0xbb, 0xb3, 0x2d, 0xb8, 0x0f, 0xd3, 0x89, 0x24,\n                                  0x5a, 0xc3, 0x7a, 0x94, 0x8e, 0x50])\n\n        bobPublic = bytearray([0x05, 0xab, 0xb8, 0xeb, 0x29, 0xcc, 0x80, 0xb4, 0x71, 0x09, 0xa2, 0x26, 0x5a, 0xbe,\n                               0x97, 0x98, 0x48, 0x54, 0x06, 0xe3, 0x2d, 0xa2, 0x68, 0x93, 0x4a, 0x95, 0x55, 0xe8,\n                               0x47, 0x57, 0x70, 0x8a, 0x30])\n\n        nextRoot = bytearray([0xb1, 0x14, 0xf5, 0xde, 0x28, 0x01, 0x19, 0x85, 0xe6, 0xeb, 0xa2, 0x5d, 0x50, 0xe7,\n                              0xec, 0x41, 0xa9, 0xb0, 0x2f, 0x56, 0x93, 0xc5, 0xc7, 0x88, 0xa6, 0x3a, 0x06, 0xd2,\n                              0x12, 0xa2, 0xf7, 0x31])\n\n        nextChain = bytearray([0x9d, 0x7d, 0x24, 0x69, 0xbc, 0x9a, 0xe5, 0x3e, 0xe9, 0x80, 0x5a, 0xa3, 0x26, 0x4d,\n                               0x24, 0x99, 0xa3, 0xac, 0xe8, 0x0f, 0x4c, 0xca, 0xe2, 0xda, 0x13, 0x43, 0x0c, 0x5c,\n                               0x55, 0xb5, 0xca, 0x5f])\n\n        alicePublicKey = Curve.decodePoint(alicePublic, 0)\n        alicePrivateKey = Curve.decodePrivatePoint(alicePrivate)\n        aliceKeyPair = ECKeyPair(alicePublicKey, alicePrivateKey)\n        bobPublicKey = Curve.decodePoint(bobPublic, 0)\n        rootKey = RootKey(HKDF.createFor(2), rootKeySeed)\n        rootKeyChainKeyPair = rootKey.createChain(bobPublicKey, aliceKeyPair)\n\n        nextRootKey = rootKeyChainKeyPair[0]\n        nextChainKey = rootKeyChainKeyPair[1]\n\n        self.assertEqual(rootKey.getKeyBytes(), rootKeySeed)\n        self.assertEqual(nextRootKey.getKeyBytes(), nextRoot)\n        self.assertEqual(nextChainKey.getKey(), nextChain)\n"
  },
  {
    "path": "axolotl/tests/test_sessionbuilder.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\nimport time\nimport sys\n\nfrom ..invalidkeyexception import InvalidKeyException\nfrom ..sessionbuilder import SessionBuilder\nfrom ..sessioncipher import SessionCipher\nfrom ..ecc.curve import Curve\nfrom ..protocol.ciphertextmessage import CiphertextMessage\nfrom ..protocol.whispermessage import WhisperMessage\nfrom ..protocol.prekeywhispermessage import PreKeyWhisperMessage\nfrom ..state.prekeybundle import PreKeyBundle\nfrom ..tests.inmemoryaxolotlstore import InMemoryAxolotlStore\nfrom ..state.prekeyrecord import PreKeyRecord\nfrom ..state.signedprekeyrecord import SignedPreKeyRecord\nfrom ..tests.inmemoryidentitykeystore import InMemoryIdentityKeyStore\nfrom ..protocol.keyexchangemessage import KeyExchangeMessage\nfrom ..untrustedidentityexception import UntrustedIdentityException\n\n\nclass SessionBuilderTest(unittest.TestCase):\n    ALICE_RECIPIENT_ID = 5\n    BOB_RECIPIENT_ID = 2\n\n    def test_basicPreKeyV2(self):\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID,\n                                             1)\n\n        bobStore = InMemoryAxolotlStore()\n        bobPreKeyPair = Curve.generateKeyPair()\n        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337, bobPreKeyPair.getPublicKey(),\n                                 0, None, None, bobStore.getIdentityKeyPair().getPublicKey())\n\n        try:\n            aliceSessionBuilder.processPreKeyBundle(bobPreKey)\n            raise AssertionError(\"Should fail with missing unsigned prekey!\");\n        except InvalidKeyException:\n            # good\n            pass\n\n        return\n\n    def test_basicPreKeyV3(self):\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID,\n                                             1)\n\n        bobStore = InMemoryAxolotlStore()\n        bobPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),\n                                                            bobSignedPreKeyPair.getPublicKey().serialize())\n\n        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337, bobPreKeyPair.getPublicKey(),\n                                 22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,\n                                 bobStore.getIdentityKeyPair().getPublicKey())\n\n        aliceSessionBuilder.processPreKeyBundle(bobPreKey)\n        self.assertTrue(aliceStore.containsSession(self.__class__.BOB_RECIPIENT_ID, 1))\n        self.assertTrue(aliceStore.loadSession(self.__class__.BOB_RECIPIENT_ID,\n                                               1).getSessionState().getSessionVersion() == 3)\n\n        originalMessage = b\"L'homme est condamne a etre libre\"\n        aliceSessionCipher = SessionCipher(aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           self.__class__.BOB_RECIPIENT_ID,\n                                           1)\n        outgoingMessage = aliceSessionCipher.encrypt(originalMessage)\n\n        self.assertTrue(outgoingMessage.getType() == CiphertextMessage.PREKEY_TYPE)\n\n        incomingMessage = PreKeyWhisperMessage(serialized=outgoingMessage.serialize())\n        bobStore.storePreKey(31337, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))\n        bobStore.storeSignedPreKey(22, SignedPreKeyRecord(22,\n                                                          int(time.time() * 1000),\n                                                          bobSignedPreKeyPair,\n                                                          bobSignedPreKeySignature))\n\n        bobSessionCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)\n\n        plaintext = bobSessionCipher.decryptPkmsg(incomingMessage)\n        self.assertEqual(originalMessage, plaintext)\n        # @@TODO: in callback assertion\n        # self.assertFalse(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))\n\n        self.assertTrue(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))\n\n        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID,\n                                             1).getSessionState().getSessionVersion() == 3)\n        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID,\n                                             1).getSessionState().getAliceBaseKey() is not None)\n        self.assertEqual(originalMessage, plaintext)\n\n        bobOutgoingMessage = bobSessionCipher.encrypt(originalMessage)\n        self.assertTrue(bobOutgoingMessage.getType() == CiphertextMessage.WHISPER_TYPE)\n\n        alicePlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobOutgoingMessage.serialize()))\n\n        self.assertEqual(alicePlaintext, originalMessage)\n\n        self.runInteraction(aliceStore, bobStore)\n\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID,\n                                             1)\n        aliceSessionCipher = SessionCipher(aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           self.__class__.BOB_RECIPIENT_ID,\n                                           1)\n\n        bobPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),\n                                                            bobSignedPreKeyPair.getPublicKey().serialize())\n        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31338, bobPreKeyPair.getPublicKey(),\n                                 23, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,\n                                 bobStore.getIdentityKeyPair().getPublicKey())\n\n        bobStore.storePreKey(31338, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))\n        bobStore.storeSignedPreKey(23, SignedPreKeyRecord(23,\n                                                          int(time.time() * 1000),\n                                                          bobSignedPreKeyPair,\n                                                          bobSignedPreKeySignature))\n        aliceSessionBuilder.processPreKeyBundle(bobPreKey)\n\n        outgoingMessage = aliceSessionCipher.encrypt(originalMessage)\n\n        try:\n            plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage))\n            raise AssertionError(\"shouldn't be trusted!\")\n        except Exception:\n            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID,\n                                  PreKeyWhisperMessage(serialized=outgoingMessage.serialize()).getIdentityKey())\n\n        plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage.serialize()))\n\n        self.assertEqual(plaintext, originalMessage)\n\n        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1, 31337,\n                                 Curve.generateKeyPair().getPublicKey(), 23, bobSignedPreKeyPair.getPublicKey(),\n                                 bobSignedPreKeySignature, aliceStore.getIdentityKeyPair().getPublicKey())\n        try:\n            aliceSessionBuilder.process(bobPreKey)\n            raise AssertionError(\"shouldn't be trusted!\")\n        except Exception:\n            # good\n            pass\n\n    def test_badSignedPreKeySignature(self):\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore, aliceStore, aliceStore, aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID, 1)\n\n        bobIdentityKeyStore = InMemoryIdentityKeyStore()\n\n        bobPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeyPair = Curve.generateKeyPair()\n        bobSignedPreKeySignature = Curve.calculateSignature(bobIdentityKeyStore.getIdentityKeyPair().getPrivateKey(),\n                                                            bobSignedPreKeyPair.getPublicKey().serialize())\n\n        for i in range(0, len(bobSignedPreKeySignature) * 8):\n            modifiedSignature = bytearray(bobSignedPreKeySignature[:])\n            modifiedSignature[int(i/8)] ^= 0x01 << (i % 8)\n\n            bobPreKey = PreKeyBundle(bobIdentityKeyStore.getLocalRegistrationId(), 1, 31337,\n                                     bobPreKeyPair.getPublicKey(), 22, bobSignedPreKeyPair.getPublicKey(),\n                                     modifiedSignature, bobIdentityKeyStore.getIdentityKeyPair().getPublicKey())\n\n            try:\n                aliceSessionBuilder.processPreKeyBundle(bobPreKey)\n            except Exception:\n                # good\n                pass\n        bobPreKey = PreKeyBundle(bobIdentityKeyStore.getLocalRegistrationId(), 1, 31337,\n                                 bobPreKeyPair.getPublicKey(), 22, bobSignedPreKeyPair.getPublicKey(),\n                                 bobSignedPreKeySignature, bobIdentityKeyStore.getIdentityKeyPair().getPublicKey())\n\n        aliceSessionBuilder.processPreKeyBundle(bobPreKey)\n\n    def test_basicKeyExchange(self):\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID,\n                                             1)\n\n        bobStore = InMemoryAxolotlStore()\n        bobSessionBuilder = SessionBuilder(bobStore,\n                                           bobStore,\n                                           bobStore,\n                                           bobStore,\n                                           self.__class__.ALICE_RECIPIENT_ID,\n                                           1)\n\n        aliceKeyExchangeMessage = aliceSessionBuilder.processInitKeyExchangeMessage()\n        self.assertTrue(aliceKeyExchangeMessage is not None)\n\n        aliceKeyExchangeMessageBytes = aliceKeyExchangeMessage.serialize()\n        bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(KeyExchangeMessage(\n            serialized=aliceKeyExchangeMessageBytes))\n\n        self.assertTrue(bobKeyExchangeMessage is not None)\n\n        bobKeyExchangeMessageBytes = bobKeyExchangeMessage.serialize()\n        response = aliceSessionBuilder.processKeyExchangeMessage(KeyExchangeMessage(\n            serialized=bobKeyExchangeMessageBytes))\n\n        self.assertTrue(response is None)\n        self.assertTrue(aliceStore.containsSession(self.__class__.BOB_RECIPIENT_ID, 1))\n        self.assertTrue(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))\n\n        self.runInteraction(aliceStore, bobStore)\n\n        aliceStore = InMemoryAxolotlStore()\n        aliceSessionBuilder = SessionBuilder(aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             aliceStore,\n                                             self.__class__.BOB_RECIPIENT_ID,\n                                             1)\n        aliceKeyExchangeMessage = aliceSessionBuilder.processInitKeyExchangeMessage()\n\n        try:\n            bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(aliceKeyExchangeMessage)\n            raise AssertionError(\"This identity shouldn't be trusted!\")\n        except UntrustedIdentityException:\n            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID, aliceKeyExchangeMessage.getIdentityKey())\n        bobKeyExchangeMessage = bobSessionBuilder.processKeyExchangeMessage(aliceKeyExchangeMessage)\n\n        self.assertTrue(aliceSessionBuilder.processKeyExchangeMessage(bobKeyExchangeMessage) == None)\n\n        self.runInteraction(aliceStore, bobStore)\n\n    def runInteraction(self, aliceStore, bobStore):\n        \"\"\"\n        :type aliceStore: AxolotlStore\n        :type  bobStore: AxolotlStore\n        \"\"\"\n        aliceSessionCipher = SessionCipher(aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           aliceStore,\n                                           self.__class__.BOB_RECIPIENT_ID,\n                                           1)\n        bobSessionCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)\n\n        originalMessage = b\"smert ze smert\"\n        aliceMessage = aliceSessionCipher.encrypt(originalMessage)\n\n        self.assertTrue(aliceMessage.getType() == CiphertextMessage.WHISPER_TYPE)\n\n        plaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceMessage.serialize()))\n\n        self.assertEqual(plaintext, originalMessage)\n\n        bobMessage = bobSessionCipher.encrypt(originalMessage)\n\n        self.assertTrue(bobMessage.getType() == CiphertextMessage.WHISPER_TYPE)\n\n        plaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobMessage.serialize()))\n\n        self.assertEqual(plaintext, originalMessage)\n\n        for i in range(0, 10):\n            loopingMessage = b\"What do we mean by saying that existence precedes essence? \" \\\n                             b\"We mean that man first of all exists, encounters himself, \" \\\n                             b\"surges up in the world--and defines himself aftward. %d\" % i\n            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)\n            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))\n\n            self.assertEqual(loopingPlaintext, loopingMessage)\n\n        for i in range(0, 10):\n            loopingMessage = b\"What do we mean by saying that existence precedes essence? \" \\\n                 b\"We mean that man first of all exists, encounters himself, \" \\\n                 b\"surges up in the world--and defines himself aftward. %d\" % i\n            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)\n\n            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))\n\n            self.assertEqual(loopingPlaintext, loopingMessage)\n\n        aliceOutOfOrderMessages = []\n\n        for i in range(0, 10):\n            loopingMessage = b\"What do we mean by saying that existence precedes essence? \" \\\n                 b\"We mean that man first of all exists, encounters himself, \" \\\n                 b\"surges up in the world--and defines himself aftward. %d\" % i\n            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)\n            aliceOutOfOrderMessages.append((loopingMessage, aliceLoopingMessage))\n\n        for i in range(0, 10):\n            loopingMessage = b\"What do we mean by saying that existence precedes essence? \" \\\n                 b\"We mean that man first of all exists, encounters himself, \" \\\n                 b\"surges up in the world--and defines himself aftward. %d\" % i\n            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)\n            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))\n\n            self.assertEqual(loopingPlaintext, loopingMessage)\n\n        for i in range(0, 10):\n            loopingMessage = b\"You can only desire based on what you know: %d\" % i\n            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)\n\n            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))\n\n            self.assertEqual(loopingPlaintext, loopingMessage)\n\n        for aliceOutOfOrderMessage in aliceOutOfOrderMessages:\n            outOfOrderPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(\n                serialized=aliceOutOfOrderMessage[1].serialize()))\n\n            self.assertEqual(outOfOrderPlaintext, aliceOutOfOrderMessage[0])\n"
  },
  {
    "path": "axolotl/tests/test_sessioncipher.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ..state.sessionrecord import SessionRecord\nfrom ..ecc.curve import Curve\nfrom ..identitykeypair import IdentityKeyPair, IdentityKey\nfrom ..ratchet.aliceaxolotlparameters import AliceAxolotlParameters\nfrom ..ratchet.bobaxolotlparamaters import BobAxolotlParameters\nfrom ..ratchet.ratchetingsession import RatchetingSession\nfrom ..tests.inmemoryaxolotlstore import InMemoryAxolotlStore\nfrom ..sessioncipher import SessionCipher\nfrom ..protocol.whispermessage import WhisperMessage\n\n\nclass SessionCipherTest(unittest.TestCase):\n\n    def test_basicSessionV3(self):\n        aliceSessionRecord = SessionRecord()\n        bobSessionRecord = SessionRecord()\n        self.initializeSessionsV3(aliceSessionRecord.getSessionState(), bobSessionRecord.getSessionState())\n        self.runInteraction(aliceSessionRecord, bobSessionRecord)\n\n    def runInteraction(self, aliceSessionRecord, bobSessionRecord):\n        aliceStore = InMemoryAxolotlStore()\n        bobStore = InMemoryAxolotlStore()\n\n        aliceStore.storeSession(2, 1, aliceSessionRecord)\n        bobStore.storeSession(3, 1, bobSessionRecord)\n\n        aliceCipher = SessionCipher(aliceStore, aliceStore, aliceStore, aliceStore, 2, 1)\n        bobCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, 3, 1)\n\n        alicePlaintext = b\"This is a plaintext message.\"\n        message = aliceCipher.encrypt(alicePlaintext)\n        bobPlaintext = bobCipher.decryptMsg(WhisperMessage(serialized=message.serialize()))\n\n        self.assertEqual(alicePlaintext, bobPlaintext)\n\n        bobReply = b\"This is a message from Bob.\"\n        reply = bobCipher.encrypt(bobReply)\n        receivedReply = aliceCipher.decryptMsg(WhisperMessage(serialized=reply.serialize()))\n\n        self.assertEqual(bobReply, receivedReply)\n\n        alicePlaintext = b\"ABCDEFGHIJKLMNOP\"  # ensure padding/unpadding properly applies on message of blocksize length\n        message = aliceCipher.encrypt(alicePlaintext)\n        bobPlaintext = bobCipher.decryptMsg(WhisperMessage(serialized=message.serialize()))\n        self.assertEqual(alicePlaintext, bobPlaintext)\n\n        aliceCiphertextMessages = []\n        alicePlaintextMessages = []\n\n        for i in range(0, 50):\n            alicePlaintextMessages.append(b\"aaaaaa %d\" % i)\n            aliceCiphertextMessages.append(aliceCipher.encrypt(b\"aaaaaa %d\" % i))\n\n        # shuffle(aliceCiphertextMessages)\n        # shuffle(alicePlaintextMessages)\n\n        for i in range(0, int(len(aliceCiphertextMessages)/2)):\n            receivedPlaintext = bobCipher.decryptMsg(WhisperMessage(serialized=aliceCiphertextMessages[i].serialize()))\n            self.assertEqual(receivedPlaintext, alicePlaintextMessages[i])\n\n    def initializeSessionsV3(self, aliceSessionState, bobSessionState):\n        aliceIdentityKeyPair = Curve.generateKeyPair()\n        aliceIdentityKey = IdentityKeyPair(IdentityKey(aliceIdentityKeyPair.getPublicKey()),\n                                           aliceIdentityKeyPair.getPrivateKey())\n        aliceBaseKey = Curve.generateKeyPair()\n        # aliceEphemeralKey = Curve.generateKeyPair()\n\n        # alicePreKey = aliceBaseKey\n\n        bobIdentityKeyPair = Curve.generateKeyPair()\n        bobIdentityKey = IdentityKeyPair(IdentityKey(bobIdentityKeyPair.getPublicKey()),\n                                         bobIdentityKeyPair.getPrivateKey())\n        bobBaseKey = Curve.generateKeyPair()\n        bobEphemeralKey = bobBaseKey\n\n        # bobPreKey = Curve.generateKeyPair()\n\n        aliceParameters = AliceAxolotlParameters.newBuilder()\\\n            .setOurBaseKey(aliceBaseKey)\\\n            .setOurIdentityKey(aliceIdentityKey)\\\n            .setTheirOneTimePreKey(None)\\\n            .setTheirRatchetKey(bobEphemeralKey.getPublicKey())\\\n            .setTheirSignedPreKey(bobBaseKey.getPublicKey())\\\n            .setTheirIdentityKey(bobIdentityKey.getPublicKey())\\\n            .create()\n\n        bobParameters = BobAxolotlParameters.newBuilder()\\\n            .setOurRatchetKey(bobEphemeralKey)\\\n            .setOurSignedPreKey(bobBaseKey)\\\n            .setOurOneTimePreKey(None)\\\n            .setOurIdentityKey(bobIdentityKey)\\\n            .setTheirIdentityKey(aliceIdentityKey.getPublicKey())\\\n            .setTheirBaseKey(aliceBaseKey.getPublicKey())\\\n            .create()\n\n        RatchetingSession.initializeSessionAsAlice(aliceSessionState, aliceParameters)\n        RatchetingSession.initializeSessionAsBob(bobSessionState, bobParameters)\n"
  },
  {
    "path": "axolotl/tests/test_sigs.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ..ecc.curve import Curve\nfrom ..util.keyhelper import KeyHelper\n\n\nclass Curve25519Test(unittest.TestCase):\n    def test_agreement(self):\n        alicePublic = bytearray([0x05, 0x1b, 0xb7, 0x59, 0x66, 0xf2, 0xe9, 0x3a, 0x36, 0x91, 0xdf, 0xff, 0x94,\n                                 0x2b, 0xb2, 0xa4, 0x66, 0xa1, 0xc0, 0x8b, 0x8d, 0x78, 0xca, 0x3f, 0x4d, 0x6d,\n                                 0xf8, 0xb8, 0xbf, 0xa2, 0xe4, 0xee, 0x28])\n        alicePrivate = bytearray([0xc8, 0x06, 0x43, 0x9d, 0xc9, 0xd2, 0xc4, 0x76, 0xff, 0xed, 0x8f, 0x25, 0x80,\n                                  0xc0, 0x88, 0x8d, 0x58, 0xab, 0x40, 0x6b, 0xf7, 0xae, 0x36, 0x98, 0x87, 0x90,\n                                  0x21, 0xb9, 0x6b, 0xb4, 0xbf, 0x59])\n\n        bobPublic = bytearray([0x05, 0x65, 0x36, 0x14, 0x99, 0x3d, 0x2b, 0x15, 0xee, 0x9e, 0x5f, 0xd3, 0xd8, 0x6c,\n                               0xe7, 0x19, 0xef, 0x4e, 0xc1, 0xda, 0xae, 0x18, 0x86, 0xa8, 0x7b, 0x3f, 0x5f, 0xa9,\n                               0x56, 0x5a, 0x27, 0xa2, 0x2f])\n\n        bobPrivate = bytearray([0xb0, 0x3b, 0x34, 0xc3, 0x3a, 0x1c, 0x44, 0xf2, 0x25, 0xb6, 0x62, 0xd2, 0xbf,\n                                0x48, 0x59, 0xb8, 0x13, 0x54, 0x11, 0xfa, 0x7b, 0x03, 0x86, 0xd4, 0x5f, 0xb7,\n                                0x5d, 0xc5, 0xb9, 0x1b, 0x44, 0x66])\n\n        shared = bytearray([0x32, 0x5f, 0x23, 0x93, 0x28, 0x94, 0x1c, 0xed, 0x6e, 0x67, 0x3b, 0x86, 0xba, 0x41,\n                            0x01, 0x74, 0x48, 0xe9, 0x9b, 0x64, 0x9a, 0x9c, 0x38, 0x06, 0xc1, 0xdd, 0x7c, 0xa4,\n                            0xc4, 0x77, 0xe6, 0x29])\n\n        alicePublicKey = Curve.decodePoint(alicePublic, 0)\n        alicePrivateKey = Curve.decodePrivatePoint(alicePrivate)\n\n        bobPublicKey = Curve.decodePoint(bobPublic, 0)\n        bobPrivateKey = Curve.decodePrivatePoint(bobPrivate)\n\n        sharedOne = Curve.calculateAgreement(alicePublicKey, bobPrivateKey)\n        sharedTwo = Curve.calculateAgreement(bobPublicKey, alicePrivateKey)\n\n        self.assertEqual(sharedOne, shared)\n        self.assertEqual(sharedTwo, shared)\n\n    def test_randomAgreements(self):\n\n        for i in range(0, 50):\n            alice = Curve.generateKeyPair()\n            bob = Curve.generateKeyPair()\n            sharedAlice = Curve.calculateAgreement(bob.getPublicKey(), alice.getPrivateKey())\n            sharedBob = Curve.calculateAgreement(alice.getPublicKey(), bob.getPrivateKey())\n            self.assertEqual(sharedAlice, sharedBob)\n\n    def test_gensig(self):\n        identityKeyPair = KeyHelper.generateIdentityKeyPair()\n        KeyHelper.generateSignedPreKey(identityKeyPair, 0)\n\n    def test_signature(self):\n        # aliceIdentityPrivate = bytearray([0xc0, 0x97, 0x24, 0x84, 0x12, 0xe5, 0x8b, 0xf0, 0x5d, 0xf4, 0x87, 0x96,\n        #                                   0x82, 0x05, 0x13, 0x27, 0x94, 0x17, 0x8e, 0x36, 0x76, 0x37, 0xf5, 0x81,\n        #                                   0x8f, 0x81, 0xe0, 0xe6, 0xce, 0x73, 0xe8, 0x65])\n\n        aliceIdentityPublic = bytearray([0x05, 0xab, 0x7e, 0x71, 0x7d, 0x4a, 0x16, 0x3b, 0x7d, 0x9a, 0x1d, 0x80,\n                                         0x71, 0xdf, 0xe9, 0xdc, 0xf8, 0xcd, 0xcd, 0x1c, 0xea, 0x33, 0x39, 0xb6,\n                                         0x35, 0x6b, 0xe8, 0x4d, 0x88, 0x7e, 0x32, 0x2c, 0x64])\n\n        aliceEphemeralPublic = bytearray([0x05, 0xed, 0xce, 0x9d, 0x9c, 0x41, 0x5c, 0xa7, 0x8c, 0xb7, 0x25, 0x2e,\n                                          0x72, 0xc2, 0xc4, 0xa5, 0x54, 0xd3, 0xeb, 0x29, 0x48, 0x5a, 0x0e, 0x1d,\n                                          0x50, 0x31, 0x18, 0xd1, 0xa8, 0x2d, 0x99, 0xfb, 0x4a])\n\n        aliceSignature = bytearray([0x5d, 0xe8, 0x8c, 0xa9, 0xa8, 0x9b, 0x4a, 0x11, 0x5d, 0xa7, 0x91, 0x09, 0xc6,\n                                    0x7c, 0x9c, 0x74, 0x64, 0xa3, 0xe4, 0x18, 0x02, 0x74, 0xf1, 0xcb, 0x8c, 0x63,\n                                    0xc2, 0x98, 0x4e, 0x28, 0x6d, 0xfb, 0xed, 0xe8, 0x2d, 0xeb, 0x9d, 0xcd, 0x9f,\n                                    0xae, 0x0b, 0xfb, 0xb8, 0x21, 0x56, 0x9b, 0x3d, 0x90, 0x01, 0xbd, 0x81, 0x30,\n                                    0xcd, 0x11, 0xd4, 0x86, 0xce, 0xf0, 0x47, 0xbd, 0x60, 0xb8, 0x6e, 0x88])\n\n        # alicePrivateKey = Curve.decodePrivatePoint(aliceIdentityPrivate)\n        alicePublicKey = Curve.decodePoint(aliceIdentityPublic, 0)\n        aliceEphemeral = Curve.decodePoint(aliceEphemeralPublic, 0)\n\n        res = Curve.verifySignature(alicePublicKey, aliceEphemeral.serialize(), bytes(aliceSignature))\n        self.assertTrue(res)\n"
  },
  {
    "path": "axolotl/tests/util/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\n__author__ = 'tarek'\n"
  },
  {
    "path": "axolotl/tests/util/test_byteutil.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom ...util.byteutil import ByteUtil\n# from ...util.hexutil import HexUtil\n\n\nclass ByteUtilTest(unittest.TestCase):\n    def test_split(self):\n        # okm = HexUtil.decodeHex('02a9aa6c7dbd64f9d3aa92f92a277bf54609dadf0b00'\n        #                         '828acfc61e3c724b84a7bfbe5efb603030526742e3ee'\n        #                         '89c7024e884e440f1ff376bb2317b2d64deb7c8322f4'\n        #                         'c5015d9d895849411ba1d793a827')\n\n        data = [i for i in range(0, 80)]\n        a_data = [i for i in range(0, 32)]\n        b_data = [i for i in range(32, 64)]\n        c_data = [i for i in range(64, 80)]\n\n        a, b, c = ByteUtil.split(data, 32, 32, 16)\n\n        self.assertEqual(a, a_data)\n        self.assertEqual(b, b_data)\n        self.assertEqual(c, c_data)\n"
  },
  {
    "path": "axolotl/untrustedidentityexception.py",
    "content": "# -*- coding: utf-8 -*-\n\nclass UntrustedIdentityException(Exception):\n    def __init__(self, name, identityKey):\n        self.name = name\n        self.identityKey = identityKey\n\n    def getName(self):\n        return self.name\n\n    def getIdentityKey(self):\n        return self.identityKey\n"
  },
  {
    "path": "axolotl/util/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n"
  },
  {
    "path": "axolotl/util/byteutil.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass ByteUtil:\n    @staticmethod\n    def combine(*args):\n        baos = bytearray()\n        for a in args:\n            if type(a) in (list, bytearray, str, bytes):\n                baos.extend(a)\n            else:\n                baos.append(a)\n\n        return baos\n\n    # @staticmethod\n    # def xsplit(inp, firstLength, secondLength, thirdLength = None):\n    #     parts = []\n    #     parts.append(inp[:firstLength])\n    #     parts.append(inp[len(parts[0]): secondLength + 1])\n    #     if thirdLength:\n    #         parts.append(inp[len(parts[1]): thirdLength + 1])\n    #     return parts\n\n    @staticmethod\n    def split(inp, firstLength, secondLength, thirdLength=None):\n        parts = []\n        parts.append(inp[:firstLength])\n        parts.append(inp[firstLength:firstLength + secondLength])\n        if thirdLength is not None:\n            parts.append(inp[firstLength + secondLength: firstLength + secondLength + thirdLength])\n\n        return parts\n\n    @staticmethod\n    def trim(inp, length):\n        return inp[:length]\n\n    @staticmethod\n    def intsToByteHighAndLow(highValue, lowValue):\n        highValue = ord(highValue) if type(highValue) is str else highValue\n        lowValue = ord(lowValue) if type(lowValue) is str else lowValue\n        return ((highValue << 4 | lowValue) & 0xFF) % 256\n\n    @staticmethod\n    def highBitsToInt(value):\n        bit = ord(value) if type(value) is str else value\n        return (bit & 0xFF) >> 4\n\n    @staticmethod\n    def lowBitsToInt(value):\n        return value & 0xF\n\n    @staticmethod\n    def intToByteArray(_bytes, offset, value):\n        _bytes[offset + 3] = value % 256\n        _bytes[offset + 2] = (value >> 8) % 256\n        _bytes[offset + 1] = (value >> 16) % 256\n        _bytes[offset] = (value >> 24) % 256\n\n        return 4\n"
  },
  {
    "path": "axolotl/util/hexutil.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport codecs\n\ndecode_hex = codecs.getdecoder(\"hex_codec\")\n\n\nclass HexUtil:\n    @staticmethod\n    def decodeHex(hexString):\n        result = decode_hex(hexString)[0]\n        return result\n"
  },
  {
    "path": "axolotl/util/keyhelper.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport time\nimport binascii\nimport os\nfrom random import SystemRandom\n\nfrom ..ecc.curve import Curve\nfrom ..identitykey import IdentityKey\nfrom ..identitykeypair import IdentityKeyPair\nfrom ..state.prekeyrecord import PreKeyRecord\nfrom ..state.signedprekeyrecord import SignedPreKeyRecord\nfrom .medium import Medium\n\n\nclass KeyHelper:\n    def __init__(self):\n        pass\n\n    @staticmethod\n    def generateIdentityKeyPair():\n        \"\"\"\n        Generate an identity key pair.  Clients should only do this once,\n        at install time.\n        @return the generated IdentityKeyPair.\n        \"\"\"\n        keyPair = Curve.generateKeyPair()\n        publicKey = IdentityKey(keyPair.getPublicKey())\n        serialized = '0a21056e8936e8367f768a7bba008ade7cf58407bdc7a6aae293e2c' \\\n                     'b7c06668dcd7d5e12205011524f0c15467100dd603e0d6020f4d293' \\\n                     'edfbcd82129b14a88791ac81365c'\n        serialized = binascii.unhexlify(serialized.encode())\n        identityKeyPair = IdentityKeyPair(publicKey, keyPair.getPrivateKey())\n        return identityKeyPair\n        # return IdentityKeyPair(serialized=serialized)\n\n    @staticmethod\n    def generateRegistrationId(extended_range=False):\n        \"\"\"\n        Generate a registration ID.  Clients should only do this once,\n        at install time.\n        :param extended_range: By default (false), the generated registration ID is sized to require the minimal\n        possible protobuf encoding overhead. Specify true if the caller needs the full range of MAX_INT at the cost\n        of slightly higher encoding overhead.\n        \"\"\"\n        if extended_range:\n            regId = KeyHelper.getRandomSequence(2147483646) + 1\n        else:\n            regId = KeyHelper.getRandomSequence(16380) + 1\n\n        return regId\n\n    @staticmethod\n    def getRandomSequence(max):\n        return SystemRandom().randrange(max)\n\n    @staticmethod\n    def generatePreKeys(start, count):\n        \"\"\"\n        Generate a list of PreKeys.  Clients should do this at install time, and\n        subsequently any time the list of PreKeys stored on the server runs low.\n\n        PreKey IDs are shorts, so they will eventually be repeated.  Clients should\n        store PreKeys in a circular buffer, so that they are repeated as infrequently\n        as possible.\n\n        @param start The starting PreKey ID, inclusive.\n        @param count The number of PreKeys to generate.\n        @return the list of generated PreKeyRecords.\n        \"\"\"\n        results = []\n        start -= 1\n        for i in range(0, count):\n            preKeyId = ((start + i) % (Medium.MAX_VALUE - 1)) + 1\n            results.append(PreKeyRecord(preKeyId, Curve.generateKeyPair()))\n\n        return results\n\n    @staticmethod\n    def generateSignedPreKey(identityKeyPair, signedPreKeyId):\n        keyPair = Curve.generateKeyPair()\n        signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize())\n\n        spk = SignedPreKeyRecord(signedPreKeyId, int(round(time.time() * 1000)), keyPair, signature)\n\n        return spk\n\n    @staticmethod\n    def generateSenderSigningKey():\n        return Curve.generateKeyPair()\n\n    @staticmethod\n    def generateSenderKey():\n        return os.urandom(32)\n\n    @staticmethod\n    def generateSenderKeyId():\n        return KeyHelper.getRandomSequence(2147483647)\n"
  },
  {
    "path": "axolotl/util/medium.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nclass Medium:\n    MAX_VALUE = 0xFFFFFF\n"
  },
  {
    "path": "setup.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport sys\n\nimport axolotl\nfrom setuptools import find_packages, setup\n\ndeps = ['cryptography', 'python-axolotl-curve25519>=0.4.1', 'protobuf>=3.0.0.b2']\n\nsetup(\n    name='python-axolotl',\n    version=axolotl.__version__ ,\n    packages= find_packages(),\n    install_requires = deps,\n    license='GPLv3 License',\n    author='Tarek Galal',\n    author_email='tare2.galal@gmail.com',\n    description=\"Python port of libaxolotl-android, originally written by Moxie Marlinspik\",\n    url='https://github.com/tgalal/python-axolotl',\n    download_url='https://github.com/tgalal/python-axolotl/releases',\n    platforms='any',\n    classifiers=['Development Status :: 5 - Production/Stable',\n                 'Intended Audience :: Developers',\n                 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n                 'Natural Language :: English',\n                 'Programming Language :: Python :: 2',\n                 'Programming Language :: Python :: 2.7',\n                 'Programming Language :: Python :: 3',\n                 'Programming Language :: Python :: 3.3',\n                 'Programming Language :: Python :: 3.4',\n                 'Programming Language :: Python :: 3.5',\n                 'Topic :: Security :: Cryptography',\n                 'Topic :: Software Development :: Libraries :: Python Modules']\n)\n"
  },
  {
    "path": "tox.ini",
    "content": "# Tox (http://tox.testrun.org/) is a tool for running tests\n# in multiple virtualenvs. This configuration file will run the\n# test suite on all supported python versions. To use it, \"pip install tox\"\n# and then run \"tox\" from this directory.\n\n[tox]\nskip_missing_interpreters = true\nenvlist = py26, py27, py32, py33, py35, py36, py37\n\n[testenv]\ncommands = nosetests axolotl.tests\ndeps =\n    nose\n    protobuf==3.0.0b2\n    cryptography\n    python-axolotl-curve25519\n"
  }
]