diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo new file mode 100644 index 0000000000..6c71bb6975 --- /dev/null +++ b/docs/build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: ad4aa434cfebd269fdbb85815bc6eb43 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_images/contract-irs.png b/docs/build/html/_images/contract-irs.png new file mode 100644 index 0000000000..d6d26dddc6 Binary files /dev/null and b/docs/build/html/_images/contract-irs.png differ diff --git a/docs/build/html/_images/dashboard.png b/docs/build/html/_images/dashboard.png new file mode 100644 index 0000000000..12e28f8cd0 Binary files /dev/null and b/docs/build/html/_images/dashboard.png differ diff --git a/docs/build/html/_images/login.png b/docs/build/html/_images/login.png new file mode 100644 index 0000000000..a2779c3e13 Binary files /dev/null and b/docs/build/html/_images/login.png differ diff --git a/docs/build/html/_images/merkleTree.png b/docs/build/html/_images/merkleTree.png new file mode 100644 index 0000000000..696f510450 Binary files /dev/null and b/docs/build/html/_images/merkleTree.png differ diff --git a/docs/build/html/_images/network-simulator.png b/docs/build/html/_images/network-simulator.png new file mode 100644 index 0000000000..3706064338 Binary files /dev/null and b/docs/build/html/_images/network-simulator.png differ diff --git a/docs/build/html/_images/newTransaction.png b/docs/build/html/_images/newTransaction.png new file mode 100644 index 0000000000..b01da505f9 Binary files /dev/null and b/docs/build/html/_images/newTransaction.png differ diff --git a/docs/build/html/_images/partialMerkle.png b/docs/build/html/_images/partialMerkle.png new file mode 100644 index 0000000000..a2c5af7a23 Binary files /dev/null and b/docs/build/html/_images/partialMerkle.png differ diff --git a/docs/build/html/_images/public-key-tree-2.png b/docs/build/html/_images/public-key-tree-2.png new file mode 100644 index 0000000000..5dc70e11e2 Binary files /dev/null and b/docs/build/html/_images/public-key-tree-2.png differ diff --git a/docs/build/html/_images/public-key-tree.png b/docs/build/html/_images/public-key-tree.png new file mode 100644 index 0000000000..66909de006 Binary files /dev/null and b/docs/build/html/_images/public-key-tree.png differ diff --git a/docs/build/html/_images/transactionView.png b/docs/build/html/_images/transactionView.png new file mode 100644 index 0000000000..2fbbdf2a6f Binary files /dev/null and b/docs/build/html/_images/transactionView.png differ diff --git a/docs/build/html/_images/vault.png b/docs/build/html/_images/vault.png new file mode 100644 index 0000000000..7909d92d3b Binary files /dev/null and b/docs/build/html/_images/vault.png differ diff --git a/docs/build/html/_sources/building-the-docs.txt b/docs/build/html/_sources/building-the-docs.txt new file mode 100644 index 0000000000..5d5677ee5d --- /dev/null +++ b/docs/build/html/_sources/building-the-docs.txt @@ -0,0 +1,54 @@ +Building the documentation +========================== + +The documentation is under the ``docs`` folder, and is written in reStructuredText format. Documentation in HTML format +is pre-generated, as well as code documentation, and this can be done automatically via a provided script. + +Requirements +------------ + +To build the documentation, you will need: + +* GNU Make +* Python and pip (tested with Python 2.7.10) +* Dokka: https://github.com/Kotlin/dokka +* Sphinx: http://www.sphinx-doc.org/ +* sphinx_rtd_theme: https://github.com/snide/sphinx_rtd_theme + +The Dokka JAR file needs to be placed under the ``lib`` directory within the ``r3prototyping`` directory, in order for the +script to find it, as in: + +.. sourcecode:: shell + + r3prototyping/lib/dokka.jar + +Note that to install under OS X El Capitan, you will need to tell pip to install under ``/usr/local``, which can be +done by specifying the installation target on the command line: + +.. sourcecode:: shell + + sudo -H pip install --install-option '--install-data=/usr/local' Sphinx + sudo -H pip install --install-option '--install-data=/usr/local' sphinx_rtd_theme + +Build +----- + +Once the requirements are installed, you can automatically build the HTML format user documentation and the API +documentation by running the following script: + +.. sourcecode:: shell + + docs/generate-docsite.sh + +Alternatively you can build non-HTML formats from the ``docs`` folder. Change directory to the folder and then run the +following to see a list of all available formats: + +.. sourcecode:: shell + + make + +For example to produce the documentation in HTML format: + +.. sourcecode:: shell + + make html diff --git a/docs/build/html/_sources/clientrpc.txt b/docs/build/html/_sources/clientrpc.txt new file mode 100644 index 0000000000..9da20ea54f --- /dev/null +++ b/docs/build/html/_sources/clientrpc.txt @@ -0,0 +1,85 @@ +Client RPC +========== + +There are multiple ways to interact with a node from a *client program*, but if your client is written in a JVM +compatible language the easiest way to do so is using the client library. The library connects to your running +node using a message queue protocol and then provides a simple RPC interface to interact with it. You make calls +on a Java object as normal, and the marshalling back and forth is handled for you. + +The starting point for the client library is the `CordaRPCClient`_ class. This provides a ``proxy`` method that +returns an implementation of the `CordaRPCOps`_ interface. A timeout parameter can be specified, and observables that +are returned by RPCs can be subscribed to in order to receive an ongoing stream of updates from the node. More +detail on how to use this is provided in the docs for the proxy method. + +.. warning:: The returned object is somewhat expensive to create and consumes a small amount of server side + resources. When you're done with it, cast it to ``Closeable`` or ``AutoCloseable`` and close it. Don't create + one for every call you make - create a proxy and reuse it. + +For a brief tutorial on how one can use the RPC API see :doc:`tutorial-clientrpc-api`. + +Security +-------- + +Users wanting to use the RPC library are first required to authenticate themselves with the node using a valid username +and password. These are kept in ``rpc-users.properties`` in the node base directory. This file also specifies +permissions for each user, which the RPC implementation can use to control access. The file format is described in +:doc:`corda-configuration-files`. + +Observables +----------- + +The RPC system handles observables in a special way. When a method returns an observable, whether directly or +as a sub-object of the response object graph, an observable is created on the client to match the one on the +server. Objects emitted by the server-side observable are pushed onto a queue which is then drained by the client. +The returned observable may even emit object graphs with even more observables in them, and it all works as you +would expect. + +This feature comes with a cost: the server must queue up objects emitted by the server-side observable until you +download them. Therefore RPCs that use this feature are marked with the ``@RPCReturnsObservables`` annotation, and +you are expected to subscribe to all the observables returned. If you don't want an observable then subscribe +then unsubscribe immediately to clear the buffers and indicate that you aren't interested. If your app quits then +server side resources will be freed automatically. + +When all the observables returned by an RPC are unsubscribed on the client side, that unsubscription propagates +through to the server where the corresponding server-side observables are also unsubscribed. + +.. warning:: If you leak an observable or proxy on the client side and it gets garbage collected, you will get + a warning printed to the logs and the proxy will be closed for you. But don't rely on this, as garbage + collection is non-deterministic. + +Versioning +---------- + +The client RPC protocol is versioned with a simple incrementing integer. When a proxy is created the server is +queried for its protocol version, and you can specify your minimum requirement. Methods added in later versions +are tagged with the ``@RPCSinceVersion`` annotation. If you try to use a method that the server isn't advertising +support of, an ``UnsupportedOperationException`` is thrown. If you want to know the version of the server, just +use the ``protocolVersion`` property (i.e. ``getProtocolVersion`` in Java). + +Thread safety +------------- + +A proxy is thread safe, blocking, and will only allow a single RPC to be in flight at once. Any observables that +are returned and you subscribe to will have objects emitted on a background thread. Observables returned as part +of one RPC and observables returned from another may have their callbacks invoked in parallel, but observables +returned as part of the same specific RPC invocation are processed serially and will not be invoked in parallel. + +If you want to make multiple calls to the server in parallel you can do that by creating multiple proxies, but +be aware that the server itself may *not* process your work in parallel even if you make your requests that way. + +Error handling +-------------- + +If something goes wrong with the RPC infrastructure itself, an ``RPCException`` is thrown. If you call a method that +requires a higher version of the protocol than the server supports, ``UnsupportedOperationException`` is thrown. +Otherwise, if the server implementation throws an exception, that exception is serialised and rethrown on the client +side as if it was thrown from inside the called RPC method. These exceptions can be caught as normal. + +Wire protocol +------------- + +The client RPC wire protocol is not currently documented. To use it you must use the client library provided. +This is likely to change in a future release. + +.. _CordaRPCClient: api/net.corda.client/-corda-r-p-c-client/index.html +.. _CordaRPCOps: api/net.corda.node.services.messaging/-corda-r-p-c-ops/index.html diff --git a/docs/build/html/_sources/codestyle.txt b/docs/build/html/_sources/codestyle.txt new file mode 100644 index 0000000000..aeebb4f04d --- /dev/null +++ b/docs/build/html/_sources/codestyle.txt @@ -0,0 +1,222 @@ +Code style guide +================ + +This document explains the coding style used in the R3 prototyping repository. You will be expected to follow these +recommendations when submitting patches for review. Please take the time to read them and internalise them, to save +time during code review. + +What follows are *recommendations* and not *rules*. They are in places intentionally vague, so use your good judgement +when interpreting them. + +.. note:: Parts of the codebase may not follow this style guide yet. If you see a place that doesn't, please fix it! + +1. General style +################ + +We use the standard Java coding style from Sun, adapted for Kotlin in ways that should be fairly intuitive. + +Files no longer have copyright notices at the top, and license is now specified in the global README.md file. +We do not mark classes with @author Javadoc annotations. + +In Kotlin code, KDoc is used rather than JavaDoc. It's very similar except it uses Markdown for formatting instead +of HTML tags. + +We target Java 8 and use the latest Java APIs whenever convenient. We use ``java.time.Instant`` to represent timestamps +and ``java.nio.file.Path`` to represent file paths. + +Never apply any design pattern religiously. There are no silver bullets in programming and if something is fashionable, +that doesn't mean it's always better. In particular: + +* Use functional programming patterns like map, filter, fold only where it's genuinely more convenient. Never be afraid + to use a simple imperative construct like a for loop or a mutable counter if that results in more direct, English-like + code. +* Use immutability when you don't anticipate very rapid or complex changes to the content. Immutability can help avoid + bugs, but over-used it can make code that has to adjust fields of an immutable object (in a clone) hard to read and + stress the garbage collector. When such code becomes a widespread pattern it can lead to code that is just generically + slow but without hotspots. +* The tradeoffs between various thread safety techniques are complex, subtle, and no technique is always superior to + the others. Our code uses a mix of locks, worker threads and messaging depending on the situation. + +1.1 Line Length and Spacing +--------------------------- + +We aim for line widths of no more than 120 characters. That is wide enough to avoid lots of pointless wrapping but +narrow enough that with a widescreen monitor and a 12 point fixed width font (like Menlo) you can fit two files +next to each other. This is not a rigidly enforced rule and if wrapping a line would be excessively awkward, let it +overflow. Overflow of a few characters here and there isn't a big deal: the goal is general convenience. + +Where the number of parameters in a function, class, etc. causes an overflow past the end of the first line, they should +be structured one parameter per line. + +Code is vertically dense, blank lines in methods are used sparingly. This is so more code can fit on screen at once. + +We use spaces and not tabs. + +1.2 Naming +---------- + +Naming generally follows Java standard style (pascal case for class names, camel case for methods, properties and +variables). Where a class name describes a tuple, "And" should be included in order to clearly indicate the elements are +individual parts, for example ``PartyAndReference``, not ``PartyReference`` (which sounds like a reference to a +``Party``). + +2. Comments +########### + +We like them as long as they add detail that is missing from the code. Comments that simply repeat the story already +told by the code are best deleted. Comments should: + +* Explain what the code is doing at a higher level than is obtainable from just examining the statement and + surrounding code. +* Explain why certain choices were made and the tradeoffs considered. +* Explain how things can go wrong, which is a detail often not easily seen just by reading the code. +* Use good grammar with capital letters and full stops. This gets us in the right frame of mind for writing real + explanations of things. + +When writing code, imagine that you have an intelligent colleague looking over your shoulder asking you questions +as you go. Think about what they might ask, and then put your answers in the code. + +Don’t be afraid of redundancy, many people will start reading your code in the middle with little or no idea of what +it’s about, eg, due to a bug or a need to introduce a new feature. It’s OK to repeat basic facts or descriptions in +different places if that increases the chance developers will see something important. + +API docs: all public methods, constants and classes should have doc comments in either JavaDoc or KDoc. API docs should: + +* Explain what the method does in words different to how the code describes it. +* Always have some text, annotation-only JavaDocs don’t render well. Write “Returns a blah blah blah” rather + than “@returns blah blah blah” if that's the only content (or leave it out if you have nothing more to say than the + code already says). +* Illustrate with examples when you might want to use the method or class. Point the user at alternatives if this code + is not always right. +* Make good use of {@link} annotations. + +Bad JavaDocs look like this: + +.. sourcecode:: java + + /** @return the size of the Bloom filter. */ + public int getBloomFilterSize() { + return block; + } + +Good JavaDocs look like this: + +.. sourcecode:: java + + /** + * Returns the size of the current {@link BloomFilter} in bytes. Larger filters have + * lower false positive rates for the same number of inserted keys and thus lower privacy, + * but bandwidth usage is also correspondingly reduced. + */ + public int getBloomFilterSize() { ... } + +We use C-style (``/** */``) comments for API docs and we use C++ style comments (``//``) for explanations that are +only intended to be viewed by people who read the code. +When writing multi-line TODO comments, indent the body text past the TODO line, for example: + +.. sourcecode:: java + + // TODO: Something something + // More stuff to do + // Etc. etc. + +3. Threading +############ + +Classes that are thread safe should be annotated with the ``@ThreadSafe`` annotation. The class or method comments +should describe how threads are expected to interact with your code, unless it's obvious because the class is +(for example) a simple immutable data holder. + +Code that supports callbacks or event listeners should always accept an ``Executor`` argument that defaults to +``MoreExecutors.directThreadExecutor()`` (i.e. the calling thread) when registering the callback. This makes it easy +to integrate the callbacks with whatever threading environment the calling code expects, e.g. serialised onto a single +worker thread if necessary, or run directly on the background threads used by the class if the callback is thread safe +and doesn't care in what context it's invoked. + +In the prototyping code it's OK to use synchronised methods i.e. with an exposed lock when the use of locking is quite +trivial. If the synchronisation in your code is getting more complex, consider the following: + +1. Is the complexity necessary? At this early stage, don't worry too much about performance or scalability, as we're + exploring the design space rather than making an optimal implementation of a design that's already nailed down. +2. Could you simplify it by making the data be owned by a dedicated, encapsulated worker thread? If so, remember to + think about flow control and what happens if a work queue fills up: the actor model can often be useful but be aware + of the downsides and try to avoid explicitly defining messages, prefer to send closures onto the worker thread + instead. +3. If you use an explicit lock and the locking gets complex, and *always* if the class supports callbacks, use the + cycle detecting locks from the Guava library. +4. Can you simplify some things by using thread-safe collections like ``CopyOnWriteArrayList`` or ``ConcurrentHashMap``? + These data structures are more expensive than their non-thread-safe equivalents but can be worth it if it lets us + simplify the code. + +Immutable data structures can be very useful for making it easier to reason about multi-threaded code. Kotlin makes it +easy to define these via the "data" attribute, which auto-generates a copy() method. That lets you create clones of +an immutable object with arbitrary fields adjusted in the clone. But if you can't use the data attribute for some +reason, for instance, you are working in Java or because you need an inheritance heirarchy, then consider that making +a class fully immutable may result in very awkward code if there's ever a need to make complex changes to it. If in +doubt, ask. Remember, never apply any design pattern religiously. + +We have an extension to the ``Executor`` interface called ``AffinityExecutor``. It is useful when the thread safety +of a piece of code is based on expecting to be called from a single thread only (or potentially, a single thread pool). +``AffinityExecutor`` has additional methods that allow for thread assertions. These can be useful to ensure code is not +accidentally being used in a multi-threaded way when it didn't expect that. + +4. Assertions and errors +######################## + +We use them liberally and we use them at runtime, in production. That means we avoid the "assert" keyword in Java, +and instead prefer to use the ``check()`` or ``require()`` functions in Kotlin (for an ``IllegalStateException`` or +``IllegalArgumentException`` respectively), or the Guava ``Preconditions.check`` method from Java. + +We define new exception types liberally. We prefer not to provide English language error messages in exceptions at +the throw site, instead we define new types with any useful information as fields, with a toString() method if +really necessary. In other words, don't do this: + +.. sourcecode:: java + + throw new Exception("The foo broke") + +instead do this + +.. sourcecode:: java + + class FooBrokenException extends Exception {} + throw new FooBrokenException() + +The latter is easier to catch and handle if later necessary, and the type name should explain what went wrong. + +Note that Kotlin does not require exception types to be declared in method prototypes like Java does. + +5. Properties +############# + +Where we want a public property to have one super-type in public and another sub-type in private (or internal), perhaps +to expose additional methods with a greater level of access to the code within the enclosing class, the style should be: + +.. sourcecode:: kotlin + + class PrivateFoo : PublicFoo + + private val _foo = PrivateFoo() + val foo: PublicFoo get() = _foo + +Notably: + +* The public property should have an explicit and more restrictive type, most likely a super class or interface. +* The private, backed property should begin with underscore but otherwise have the same name as the public property. + The underscore resolves a potential property name clash, and avoids naming such as "privateFoo". If the type or use + of the private property is different enough that there is no naming collision, prefer the distinct names without + an underscore. +* The underscore prefix is not a general pattern for private properties. +* The public property should not have an additional backing field but use "get()" to return an appropriate copy of the + private field. +* The public property should optionally wrap the returned value in an immutable wrapper, such as Guava's immutable + collection wrappers, if that is appropriate. +* If the code following "get()" is succinct, prefer a one-liner formatting of the public property as above, otherwise + put the "get()" on the line below, indented. + +6. Compiler warnings +#################### + +We do not allow compiler warnings, except in the experimental module where the usual standards do not apply and warnings +are suppressed. If a warning exists it should be either fixed or suppressed using @SuppressWarnings and if suppressed +there must be an accompanying explanation in the code for why the warning is a false positive. \ No newline at end of file diff --git a/docs/build/html/_sources/consensus.txt b/docs/build/html/_sources/consensus.txt new file mode 100644 index 0000000000..d0be66fa03 --- /dev/null +++ b/docs/build/html/_sources/consensus.txt @@ -0,0 +1,195 @@ +Consensus model +=============== + +The fundamental unit of consensus in Corda is the **state**. The concept of consensus can be divided into two parts: + +1. Consensus over state **validity** -- parties can reach certainty that a transaction defining output states is accepted by the contracts pointed to by the states and has all the required signatures. This is achieved by parties independently running the same contract code and validation logic (as described in :doc:`data model `) + +2. Consensus over state **uniqueness** -- parties can reach certainty the output states created in a transaction are the unique successors to the input states consumed by that transaction (in other words -- a state has not been used as an input by more than one transaction) + +This article presents an initial model for addressing the **uniqueness** problem. + +.. note:: The current model is still a **work in progress** and everything described in this article can and is likely to change + +Notary +------ + +We introduce the concept of a **notary**, which is an authority responsible for attesting that for a given transaction, it had not signed another transaction consuming any of its input states. +The data model is extended so that every **state** has an appointed notary: + +.. sourcecode:: kotlin + + /** + * A wrapper for [ContractState] containing additional platform-level state information. + * This is the definitive state that is stored on the ledger and used in transaction outputs + */ + data class TransactionState( + /** The custom contract state */ + val data: T, + /** Identity of the notary that ensures the state is not used as an input to a transaction more than once */ + val notary: Party) { + ... + } + +All transactions have to be signed by their input state notary for the output states to be **valid** (apart from *issue* transactions, containing no input states). + +.. note:: The notary is a logical concept and can itself be a distributed entity, potentially a cluster maintained by mutually distrusting parties + +When the notary is requested to sign a transaction, it either signs over it, attesting that the outputs are the **unique** successors of the inputs, +or provides conflict information for any input state that had been consumed by another transaction it had signed before. +In doing so, the notary provides the point of finality in the system. Until the notary signature is obtained, parties cannot be sure that an equally valid, but conflicting transaction, +will not be regarded as confirmed. After the signature is obtained, the parties know that the inputs to this transaction have been uniquely consumed by this transaction. +Hence it is the point at which we can say finality has occurred. + +Multiple notaries +~~~~~~~~~~~~~~~~~ + +More than one notary can exist in the network. This gives the following benefits: + +* **Custom behaviour**. We can have both validating and privacy preserving Notaries -- parties can make a choice based on their specific requirements +* **Load balancing**. Spreading the transaction load over multiple Notaries will allow higher transaction throughput in the platform overall +* **Low latency**. Latency could be minimised by choosing a notary physically closer the transacting parties + +A transaction should only be signed by a notary if all of its input states point to it. +In cases where a transaction involves states controlled by multiple notaries, the states first have to be repointed to the same notary. +This is achieved by using a special type of transaction that doesn't modify anything but the notary pointer of the state. +Ensuring that all input states point to the same notary is the responsibility of each involved party +(it is another condition for an output state of the transaction to be **valid**) + +Changing notaries +~~~~~~~~~~~~~~~~~ + +To change the notary for an input state, use the ``NotaryChangeProtocol``. For example: + +.. sourcecode:: kotlin + + @Suspendable + fun changeNotary(originalState: StateAndRef, + newNotary: Party): StateAndRef { + val protocol = NotaryChangeProtocol.Instigator(originalState, newNotary) + return subProtocol(protocol) + } + +The protocol will: + +1. Construct a transaction with the old state as the input and the new state as the output + +2. Obtain signatures from all *participants* (a participant is any party that is able to consume this state in a valid transaction, as defined by the state itself) + +3. Obtain the *old* notary signature + +4. Record and distribute the final transaction to the participants so that everyone possesses the new state + +.. note:: Eventually this will be handled automatically on demand. + +Validation +---------- + +One of the design decisions for a notary is whether or not to **validate** a transaction before committing its input states. + +If a transaction is not checked for validity, it opens the platform to "denial of state" attacks, where anyone can build an invalid transaction consuming someone else's states and submit it to the notary to get the states "blocked". +However, validation of a transaction requires the notary to be able to see the full contents of the transaction in question and its dependencies. +This is an obvious privacy leak. + +Our platform is flexible and we currently support both validating and non-validating notary implementations -- a party can select which one to use based on its own privacy requirements. + +.. note:: In the non-validating model the "denial of state" attack is partially alleviated by requiring the calling + party to authenticate and storing its identity for the request. The conflict information returned by the notary + specifies the consuming transaction ID along with the identity of the party that had requested the commit. If the + conflicting transaction is valid, the current one gets aborted; if not – a dispute can be raised and the input states + of the conflicting invalid transaction are "un-committed" (to be covered by legal process). + +.. note:: At present all notaries can see the entire contents of a transaction, but we have a separate piece of work to + replace the parts of the transaction it does not require knowing about with hashes (only input references, timestamp + information, overall transaction ID and the necessary digests of the rest of the transaction to prove that the + referenced inputs/timestamps really do form part of the stated transaction ID should be visible). + +Timestamping +------------ + +In this model the notary also acts as a *timestamping authority*, verifying the transaction timestamp command. + +For a timestamp to be meaningful, its implications must be binding on the party requesting it. +A party can obtain a timestamp signature in order to prove that some event happened before/on/or after a particular point in time. +However, if the party is not also compelled to commit to the associated transaction, it has a choice of whether or not to reveal this fact until some point in the future. +As a result, we need to ensure that the notary either has to also sign the transaction within some time tolerance, +or perform timestamping *and* notarisation at the same time, which is the chosen behaviour for this model. + +There will never be exact clock synchronisation between the party creating the transaction and the notary. +This is not only due to physics, network latencies etc but because between inserting the command and getting the +notary to sign there may be many other steps, like sending the transaction to other parties involved in the trade +as well, or even requesting human signoff. Thus the time observed by the notary may be quite different to the +time observed in step 1. + +For this reason, times in transactions are specified as time *windows*, not absolute times. Time windows can be +open-ended, i.e. specify only one of "before" and "after" or they can be fully bounded. If a time window needs to +be converted to an absolute time for e.g. display purposes, there is a utility method on ``Timestamp`` to +calculate the mid point - but in a distributed system there can never be "true time", only an approximation of it. + +In this way we express that the *true value* of the fact "the current time" is actually unknowable. Even when both before and +after times are included, the transaction could have occurred at any point between those two timestamps. Here +"occurrence" could mean the execution date, the value date, the trade date etc ... the notary doesn't care what precise +meaning the timestamp has to the contract. + +By creating a range that can be either closed or open at one end, we allow all of the following facts to be modelled: + +* This transaction occurred at some point after the given time (e.g. after a maturity event) +* This transaction occurred at any time before the given time (e.g. before a bankruptcy event) +* This transaction occurred at some point roughly around the given time (e.g. on a specific day) + +.. note:: It is assumed that the time feed for a notary is GPS/NaviStar time as defined by the atomic + clocks at the US Naval Observatory. This time feed is extremely accurate and available globally for free. + +Running a notary service +------------------------ + +At present we have two basic implementations that store committed input states in memory: + +- ``SimpleNotaryService`` -- commits the provided transaction without any validation + +- ``ValidatingNotaryService`` -- retrieves and validates the whole transaction history (including the given transaction) before committing + +Obtaining a signature +--------------------- + +Once a transaction is built and ready to be finalised, normally you would call ``FinalityProtocol`` passing in a +``SignedTransaction`` (including signatures from the participants) and a list of participants to notify. This requests a +notary signature if needed, and then sends a copy of the notarised transaction to all participants for them to store. +``FinalityProtocol`` delegates to ``NotaryProtocol.Client`` followed by ``BroadcastTransactionProtocol`` to do the +actual work of notarising and broadcasting the transaction. For example: + +.. sourcecode:: kotlin + + fun finaliseTransaction(serviceHub: ServiceHubInternal, ptx: TransactionBuilder, participants: Set) + : ListenableFuture { + // We conclusively cannot have all the signatures, as the notary has not signed yet + val tx = ptx.toSignedTransaction(checkSufficientSignatures = false) + // The empty set would be the trigger events, which are not used here + val protocol = FinalityProtocol(tx, emptySet(), participants) + return serviceHub.startProtocol("protocol.finalisation", protocol) + } + +To manually obtain a signature from a notary you can call ``NotaryProtocol.Client`` directly. The protocol will work out +which notary needs to be called based on the input states and the timestamp command. For example, the following snippet +can be used when writing a custom protocol: + +.. sourcecode:: kotlin + + fun getNotarySignature(wtx: WireTransaction): DigitalSignature.LegallyIdentifiable { + return subProtocol(NotaryProtocol.Client(wtx)) + } + +On conflict the ``NotaryProtocol`` with throw a ``NotaryException`` containing the conflict details: + +.. sourcecode:: kotlin + + /** Specifies the consuming transaction for the conflicting input state */ + data class Conflict(val stateHistory: Map) + + /** + * Specifies the transaction id, the position of the consumed state in the inputs, and + * the caller identity requesting the commit + */ + data class ConsumingTx(val id: SecureHash, val inputIndex: Int, val requestingParty: Party) + +Conflict handling and resolution is currently the responsibility of the protocol author. diff --git a/docs/build/html/_sources/contract-catalogue.txt b/docs/build/html/_sources/contract-catalogue.txt new file mode 100644 index 0000000000..db52a161a2 --- /dev/null +++ b/docs/build/html/_sources/contract-catalogue.txt @@ -0,0 +1,74 @@ +Contract catalogue +================== + +There are a number of contracts supplied with Corda, which cover both core functionality (such as cash on ledger) and +provide examples of how to model complex contracts (such as interest rate swaps). There is also a ``Dummy`` contract. +However it does not provide any meaningful functionality, and is intended purely for testing purposes. + +Cash +---- + +The ``Cash`` contract's state objects represent an amount of some issued currency, owned by some party. Any currency +can be issued by any party, and it is up to the recipient to determine whether they trust the issuer. Generally nodes +are expected to have criteria (such as a whitelist) that issuers must fulfil for cash they issue to be accepted. + +Cash state objects implement the ``FungibleAsset`` interface, and can be used by the commercial paper and obligation +contracts as part of settlement of an outstanding debt. The contracts' verification functions require that cash state +objects of the correct value are received by the beneficiary as part of the settlement transaction. + +The cash contract supports issuing, moving and exiting (destroying) states. Note, however, that issuance cannot be part +of the same transaction as other cash commands, in order to minimise complexity in balance verification. + +Cash shares a common superclass, ``OnChainAsset``, with the Commodity contract. This implements common behaviour of +assets which can be issued, moved and exited on chain, with the subclasses handling asset-specific data types and +behaviour. + +Commodity +--------- + +The ``Commodity`` contract is an early stage example of a non-currency contract whose states implement the ``FungibleAsset`` +interface. This is used as a proof of concept for non-cash obligations. + +Commercial Paper +---------------- + +``CommercialPaper`` is a very simple obligation to pay an amount of cash at some future point in time (the maturity +date), and exists primarily as a simplified contract for use in tutorials. Commercial paper supports issuing, moving +and redeeming (settling) states. Unlike the full obligation contract it does not support locking the state so it cannot +be settled if the obligor defaults on payment, or netting of state objects. All commands are exclusive of the other +commercial paper commands. Use the ``Obligation`` contract for more advanced functionality. + +Interest Rate Swap +------------------ + +The Interest Rate Swap (IRS) contract is a bilateral contract to implement a vanilla fixed / floating same currency +interest rate swap. In general, an IRS allows two counterparties to modify their exposure from changes in the underlying +interest rate. They are often used as a hedging instrument, convert a fixed rate loan to a floating rate loan, vice +versa etc. + +See ":doc:`contract-irs`" for full details on the IRS contract. + +Obligation +---------- + +The obligation contract's state objects represent an obligation to provide some asset, which would generally be a +cash state object, but can be any contract state object fulfilling the ``FungibleAsset`` interface, including other +obligations. The obligation contract uses objects referred to as ``Terms`` to group commands and state objects together. +Terms are a subset of an obligation state object, including details of what should be paid, when, and to whom. + +Obligation state objects can be issued, moved and exited as with any fungible asset. The contract also supports state +object netting and lifecycle changes (marking the obligation that a state object represents as having defaulted, or +reverting it to the normal state after marking as having defaulted). The ``Net`` command cannot be included with any +other obligation commands in the same transaction, as it applies to state objects with different beneficiaries, and +as such applies across multiple terms. + +All other obligation contract commands specify obligation terms (what is to be delivered, by whom and by when) +which are used as a grouping key for input/output states and commands. Issuance and lifecyle commands are mutually +exclusive of other commands (move/exit) which apply to the same obligation terms, but multiple commands can be present +in a single transaction if they apply to different terms. For example, a contract can have two different ``Issue`` +commands as long as they apply to different terms, but could not have an ``Issue`` and a ``Net``, or an ``Issue`` and +``Move`` that apply to the same terms. + +Netting of obligations supports close-out netting (which can be triggered by either obligor or beneficiary, but is +limited to bilateral netting), and payment netting (which requires signatures from all involved parties, but supports +multilateral netting). diff --git a/docs/build/html/_sources/contract-irs.txt b/docs/build/html/_sources/contract-irs.txt new file mode 100644 index 0000000000..dbec7e166b --- /dev/null +++ b/docs/build/html/_sources/contract-irs.txt @@ -0,0 +1,107 @@ +Interest Rate Swaps +=================== + + +The Interest Rate Swap (IRS) Contract (source: IRS.kt, IRSUtils.kt, IRSExport.kt) is a bilateral contract to implement a +vanilla fixed / floating same currency IRS. + + +In general, an IRS allows two counterparties to modify their exposure from changes in the underlying interest rate. They +are often used as a hedging instrument, convert a fixed rate loan to a floating rate loan, vice versa etc. + +The IRS contract exists over a period of time (normally measurable in years). It starts on its value date +(although this is not the agreement date), and is considered to be no longer active after its maturity date. During that +time, there is an exchange of cash flows which are calculated by looking at the economics of each leg. These are based +upon an amount that is not actually exchanged but notionally used for the calculation (and is hence known as the notional +amount), and a rate that is either fixed at the creation of the swap (for the fixed leg), or based upon a reference rate +that is retrieved during the swap (for the floating leg). An example reference rate might be something such as 'LIBOR 3M'. + +The fixed leg has its rate computed and set in advance, whereas the floating leg has a fixing process whereas the rate +for the next period is fixed with relation to a reference rate. Then, a calculation is performed such that the interest +due over that period multiplied by the notional is paid (normally at the end of the period). If these two legs have the +same payment date, then these flows can be offset against each other (in reality there are normally a number of these +swaps that are live between two counterparties, so that further netting is performed at counterparty level). + +The fixed leg and floating leg do not have to have the same period frequency. In fact, conventional swaps do not have +the same period. + +Currently, there is no notion of an actual payment or obligation being performed in the contract code we have written; +it merely represents that the payment needs to be made. + +Consider the diagram below; the x-axis represents time and the y-axis the size of the leg payments (not to scale), from +the view of the floating leg receiver / fixed leg payer. The enumerated documents represent the versions of the IRS as +it progresses (note that, the first version exists before the value date), the dots on the "y=0" represent an interest +rate value becoming available and then the curved arrow indicates to which period the fixing applies. + +.. image:: contract-irs.png + +Two days (by convention, although this can be modified), before the value date (ie the start of the swap) in the red +period the reference rate is observed from an oracle and fixed in the instance at 1.1%. At the end of the accrual period, +there is an obligation from the floating leg payer of 1.1% * notional amount * days in the accrual period / 360. +(Also note that the result of "days in the accrual period / 360" is also known as the day count factor, although other +conventions are allowed and will be supported). This amount is then paid at a determined time at the end of the accrual period. + +Again, two working days before the blue period, the rate is fixed (this time at 0.5% - however in reality, the rates +would not be so significantly different), and the same calculation is performed to evaluate the payment that will be due +at the end of this period. + +This process continues until the swap reaches maturity and the final payments are calculated. + +Creating an instance and lifecycle +---------------------------------- + + +There are two valid operations on an IRS. The first is to generate via the ``Agree`` command (signed by both parties) +and the second (and repeated operation) is ``Fix`` to apply a rate fixing. +To see the minimum dataset required for the creation of an IRS, refer to ``IRSTests.kt`` which has two examples in the +function ``IRSTests.createDummyIRS()``. Implicitly, when the agree function is called, the floating leg and fixed +leg payment schedules are created (more details below) and can be queried. + +Once an IRS hase been agreed, then the the only valid operation is to apply a fixing on one of the entries in the +``Calculation.floatingLegPaymentSchedule`` map. Fixes do not have to be applied in order (although it does make most +sense to do them so). + +Examples of applying fixings to rates can been seen in ``IRSTests.generateIRSandFixSome()`` which loops through the next +fixing date of an IRS that is created with the above example function and then applies a fixing of 0.052% to each floating +event. + +Currently, there are no matured, termination or dispute operations. + + +Technical Details +----------------- + +The contract itself comprises of 4 data state classes, ``FixedLeg``, ``FloatingLeg``, ``Common`` and ``Calculation``. +Recall that the platform model is strictly immutable. To further that, between states, the only class that is modified +is the ``Calculation`` class. + +The ``Common`` data class contains all data that is general to the entire swap, e.g. data like trade identifier, +valuation date, etc. + +The Fixed and Floating leg classes derive from a common base class ``CommonLeg``. This is due to the simple reason that +they share a lot of common fields. + +The ``CommonLeg`` class contains the notional amount, a payment frequency, the effective date (as well as an adjustment +option), a termination date (and optional adjustment), the day count basis for day factor calculation, the payment delay +and calendar for the payment as well as the accrual adjustment options. + +The ``FixedLeg`` contains all the details for the ``CommonLeg`` as well as payer details, the rate the leg is fixed at +and the date roll convention (ie what to do if the calculated date lands on a bank holiday or weekend). + +The ``FloatingLeg`` contains all the details for the CommonLeg and payer details, roll convention, the fixing roll +convention, which day of the month the reset is calculated, the frequency period of the fixing, the fixing calendar and +the details for the reference index (source and tenor). + +The ``Calculation`` class contains an expression (that can be evaluated via the ledger using variables provided and also +any members of the contract) and two schedules - a ``floatingLegPaymentSchedule`` and a ``fixedLegPaymentSchedule``. +The fixed leg schedule is obviously pre-ordained, however, during the lifetime of the swap, the floating leg schedule is +regenerated upon each fixing being presented. + +For this reason, there are two helper functions on the floating leg. ``Calculation.getFixing`` returns the date of the +earliest unset fixing, and ``Calculation.applyFixing`` returns a new Calculation object with the revised fixing in place. +Note that both schedules are, for consistency, indexed by payment dates, but the fixing is (due to the convention of +taking place two days previously) not going to be on that date. + +.. note:: Payment events in the ``floatingLegPaymentSchedule`` that start as a ``FloatingRatePaymentEvent`` (which is a + representation of a payment for a rate that has not yet been finalised) are replaced in their entirety with an + equivalent ``FixedRatePaymentEvent`` (which is the same type that is on the ``FixedLeg``). diff --git a/docs/build/html/_sources/corda-configuration-files.txt b/docs/build/html/_sources/corda-configuration-files.txt new file mode 100644 index 0000000000..f24b155a55 --- /dev/null +++ b/docs/build/html/_sources/corda-configuration-files.txt @@ -0,0 +1,116 @@ +The Corda Configuration File +============================ + +Configuration File Location +--------------------------- + +The Corda all-in-one ``corda.jar`` file is generated by the ``gradle buildCordaJAR`` task and defaults to reading configuration from a ``node.conf`` file in the present working directory. +This behaviour can be overidden using the ``--config-file`` command line option to target configuration files with different names, or different file location (relative paths are relative to the current working directory). +Also, the ``--base-directory`` command line option alters the Corda node workspace location and if specified a ``node.conf`` configuration file is then expected in the root of the workspace. + +The configuration file templates used for the ``gradle installTemplateNodes`` task are to be found in the ``/config/dev`` folder. Also note that there is a basic set of defaults loaded from +the built in resource file ``/node/src/main/resources/reference.conf`` of the ``:node`` gradle module. All properties in this can be overidden in the file configuration +and for rarely changed properties this defaulting allows the property to be excluded from the configuration file. + +Configuration File Format +------------------------- + +Corda uses the Typesafe configuration library to parse the configuration see the `typesafe config on Github `_ the format of the configuration files can be simple JSON, but for the more powerful substitution features +uses HOCON format see `HOCON documents `_ + +Configuration File Examples +--------------------------- + +General node configuration file for hosting the IRSDemo services. + +.. code-block:: text + + basedir : "./nodea" + myLegalName : "Bank A" + nearestCity : "London" + keyStorePassword : "cordacadevpass" + trustStorePassword : "trustpass" + dataSourceProperties : { + dataSourceClassName : org.h2.jdbcx.JdbcDataSource + "dataSource.url" : "jdbc:h2:"${basedir}"/persistence" + "dataSource.user" : sa + "dataSource.password" : "" + } + artemisAddress : "localhost:31337" + webAddress : "localhost:31339" + extraAdvertisedServiceIds: "corda.interest_rates" + networkMapAddress : "localhost:12345" + useHTTPS : false + +NetworkMapService plus Simple Notary configuration file. + +.. code-block:: text + + basedir : "./nameserver" + myLegalName : "Notary Service" + nearestCity : "London" + keyStorePassword : "cordacadevpass" + trustStorePassword : "trustpass" + artemisAddress : "localhost:12345" + webAddress : "localhost:12346" + extraAdvertisedServiceIds: "" + useHTTPS : false + +Configuration File Fields +------------------------- + +:basedir: This specifies the node workspace folder either as an absolute path, or relative to the current working directory. It can be overidden by the ``--base-directory`` command line option, in which case the the value in the file is ignored and a ``node.conf`` file is expected in that workspace directory as the configuration source. + +:myLegalName: The legal identity of the node acts as a human readable alias to the node's public key and several demos use this to lookup the NodeInfo. + +:nearestCity: The location of the node as used to locate coordinates on the world map when running the network simulator demo. See :doc:`network-simulator`. + +:keyStorePassword: + The password to unlock the KeyStore file (``/certificates/sslkeystore.jks``) containing the node certificate and private key. + + note:: This is the non-secret value for the development certificates automatically generated during the first node run. Longer term these keys will be managed in secure hardware devices. + +:trustStorePassword: + The password to unlock the Trust store file (``/certificates/truststore.jks``) containing the R3 Corda root certificate. This is the non-secret value for the development certificates automatically generated during the first node run. + + .. note:: Longer term these keys will be managed in secure hardware devices. + +:dataSourceProperties: + This section is used to configure the jdbc connection and database driver used for the nodes persistence. Currently the defaults in ``/node/src/main/resources/reference.conf`` are as shown in the first example. This is currently the only configuration that has been tested, although in the future full support for other storage layers will be validated. + +:artemisAddress: + The host and port on which the node is available for protocol operations over ArtemisMQ. + + .. note:: In practice the ArtemisMQ messaging services bind to all local addresses on the specified port. However, note that the host is the included as the advertised entry in the NetworkMapService. As a result the value listed here must be externally accessible when running nodes across a cluster of machines. + +:messagingServerAddress: + The address of the ArtemisMQ broker instance. If not provided the node will run one locally. + +:webAddress: + The host and port on which the node is available for web operations. + + .. note:: If HTTPS is enabled then the browser security checks will require that the accessing url host name is one of either the machine name, fully qualified machine name, or server IP address to line up with the Subject Alternative Names contained within the development certificates. This is addition to requiring the ``/config/dev/corda_dev_ca.cer`` root certificate be installed as a Trusted CA. + +:extraAdvertisedServiceIds: A list of ServiceType id strings to be advertised to the NetworkMapService and thus be available when other nodes query the NetworkMapCache for supporting nodes. This can also include plugin services loaded from .jar files in the plugins folder. + +:networkMapAddress: If `null`, or missing the node is declaring itself as the NetworkMapService host. Otherwise the configuration value is the remote HostAndPort string for the ArtemisMQ service on the hosting node. + +:useHTTPS: If false the node's web server will be plain HTTP. If true the node will use the same certificate and private key from the ``/certificates/sslkeystore.jks`` file as the ArtemisMQ port for HTTPS. If HTTPS is enabled then unencrypted HTTP traffic to the node's **webAddress** port is not supported. + +RPC Users File +============== + +Corda also uses the ``rpc-users.properties`` file, found in the base directory, to control access to the RPC subsystem. +This is a Java properties file (details can be found in the `Javadocs `_) +which specifies a list of users with their password and list of permissions they're enabled for. + +.. code-block:: text + :caption: Sample + + admin=notsecure,ADMIN + user1=letmein,CASH,PAPER + +In this example ``user1`` has password ``letmein`` and has permissions for ``CASH`` and ``PAPER``. The permissions are +free-form strings which can be used by the RPC methods to control access. + +If ``rpc-users.properties`` is empty or doesn't exist then the RPC subsystem is effectively locked down. \ No newline at end of file diff --git a/docs/build/html/_sources/creating-a-cordapp.txt b/docs/build/html/_sources/creating-a-cordapp.txt new file mode 100644 index 0000000000..5b5183837a --- /dev/null +++ b/docs/build/html/_sources/creating-a-cordapp.txt @@ -0,0 +1,246 @@ +Creating a Cordapp +================== + +A Cordapp is an application that runs on the Corda platform using the platform APIs and plugin system. They are self +contained in separate JARs from the node server JAR that are created and distributed. + +App Plugins +----------- + +.. note:: Currently apps are only supported for JVM languages. + +To create an app plugin you must you must extend from `CordaPluginRegistry`_. The JavaDoc contains +specific details of the implementation, but you can extend the server in the following ways: + +1. Required protocols: Specify which protocols will be whitelisted for use in your web APIs. +2. Service plugins: Register your services (see below). +3. Web APIs: You may register your own endpoints under /api/ of the built-in web server. +4. Static web endpoints: You may register your own static serving directories for serving web content. + +Services +-------- + +Services are classes which are constructed after the node has started. It is provided a `ServiceHubInternal`_ which +allows a richer API than the `ServiceHub`_ exposed to contracts. It enables adding protocols, registering +message handlers and more. The service does not run in a separate thread, so the only entry point to the service is during +construction, where message handlers should be registered and threads started. + + +Starting Nodes +-------------- + +To use an app you must also have a node server. To create a node server run the gradle installTemplateNodes task. + +This will output the node JAR to ``build/libs/corda.jar`` and several sample/standard +node setups to ``build/nodes``. For now you can use the ``build/nodes/nodea`` configuration as a template. + +Each node server by default must have a ``node.conf`` file in the current working directory. After first +execution of the node server there will be many other configuration and persistence files created in a node workspace directory. This is specified as the basedir property of the node.conf file, or else can be overidden using ``--base-directory=``. + +.. note:: Outside of development environments do not store your node directories in the build folder. + +.. warning:: Also note that the bootstrapping process of the ``corda.jar`` unpacks the Corda dependencies into a temporary folder. It is therefore suggested that the CAPSULE_CACHE_DIR environment variable be set before starting the process to control this location. + +Installing Apps +--------------- + +Once you have created your app JAR you can install it to a node by adding it to ``/plugins/``. In this +case the ``node_dir`` is the location where your node server's JAR and configuration file is. + +.. note:: If the directory does not exist you can create it manually. + +Starting your Node +------------------ + +Now you have a node server with your app installed, you can run it by navigating to ```` and running + + java -jar corda.jar + +The plugin should automatically be registered and the configuration file used. + +.. warning:: If your working directory is not ```` your plugins and configuration will not be used. + +The configuration file and workspace paths can be overidden on the command line e.g. + +``java -jar corda.jar --config-file=test.conf --base-directory=/opt/r3corda/nodes/test``. + +Otherwise the workspace folder for the node is created based upon the ``basedir`` property in the ``node.conf`` file and if this is relative it is applied relative to the current working path. + +Debugging your Node +------------------- + +To enable remote debugging of the corda process use a command line such as: + +``java -Dcapsule.jvm.args="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005" -jar corda.jar`` + +This command line will start the debugger on port 5005 and pause the process awaiting debugger attachment. + +Viewing persisted state of your Node +------------------------------------ + +To make examining the persisted contract states of your node or the internal node database tables easier, and providing you are +using the default database configuration used for demos, you should be able to connect to the internal node database over +a JDBC connection at the URL that is output to the logs at node start up. That URL will be of the form ``jdbc:h2:tcp://:/node``. + +The user name and password for the login are as per the node data source configuration. + +The name and column layout of the internal node tables is in a state of flux and should not be relied upon to remain static +at the present time, and should certainly be treated as read-only. + +.. _CordaPluginRegistry: api/net.corda.core.node/-corda-plugin-registry/index.html +.. _ServiceHubInternal: api/net.corda.node.services.api/-service-hub-internal/index.html +.. _ServiceHub: api/net.corda.node.services.api/-service-hub/index.html + +Building Against Corda +---------------------- + +.. warning:: This feature is subject to rapid change + +Corda now supports publishing to Maven local to build against it. To publish to Maven local run the following in the +root directory of Corda + +.. code-block:: shell + + ./gradlew install + +This will publish corda-$version.jar, finance-$version.jar, core-$version.jar and node-$version.jar to the +group net.corda. You can now depend on these as you normally would a Maven dependency. + +Gradle Plugins for Cordapps +=========================== + +There are several Gradle plugins that reduce your build.gradle boilerplate and make development of Cordapps easier. +The available plugins are in the gradle-plugins directory of the Corda repository. + +Building Gradle Plugins +----------------------- + +To install to your local Maven repository the plugins that Cordapp gradle files require, run the following from the +root of the Corda project: + +.. code-block:: text + + ./gradlew install + +The plugins will now be installed to your local Maven repository in ~/.m2 on Unix and %HOMEPATH%\.m2 on Windows. + +Using Gradle Plugins +-------------------- + +To use the plugins, if you are not already using the Cordapp template project, you must modify your build.gradle. Add +the following segments to the relevant part of your build.gradle. + +Template build.gradle +--------------------- + +To build against Corda and the plugins that cordapps use, update your build.gradle to contain the following: + +.. code-block:: groovy + + buildscript { + ext.corda_version = '' + ... your buildscript ... + + repositories { + ... other repositories ... + mavenLocal() + } + + dependencies { + ... your dependencies ... + classpath "net.corda.plugins:cordformation:$corda_version" + classpath "net.corda.plugins:quasar-utils:$corda_version" + classpath "net.corda.plugins:publish-utils:$corda_version" + } + } + + apply plugin: 'net.corda.plugins.cordformation' + apply plugin: 'net.corda.plugins.quasar-utils' + apply plugin: 'net.corda.plugins.publish-utils' + + repositories { + mavenLocal() + ... other repositories here ... + } + + dependencies { + compile "net.corda.core:$corda_version" + compile "net.corda.finance:$corda_version" + compile "net.corda.node:$corda_version" + compile "net.corda.corda:$corda_version" + ... other dependencies here ... + } + + ... your tasks ... + + // Sets the classes for Quasar to scan. Loaded by the the quasar-utils plugin. + quasarScan.dependsOn('classes', ... your dependent subprojects...) + + // Standard way to publish Cordapps to maven local with the maven-publish and publish-utils plugin. + publishing { + publications { + jarAndSources(MavenPublication) { + from components.java + // The two lines below are the tasks added by this plugin. + artifact sourceJar + artifact javadocJar + } + } + } + + + +Cordformation +------------- + +Cordformation is the local node deployment system for Cordapps, the nodes generated are intended to be used for +experimenting, debugging, and testing node configurations and setups but not intended for production or testnet +deployment. + +To use this gradle plugin you must add a new task that is of the type ``net.corda.plugins.Cordform`` to your +build.gradle and then configure the nodes you wish to deploy with the Node and nodes configuration DSL. +This DSL is specified in the `JavaDoc `_. An example of this is in the template-cordapp and below +is a three node example; + +.. code-block:: text + + task deployNodes(type: net.corda.plugins.Cordform, dependsOn: ['build']) { + directory "./build/nodes" // The output directory + networkMap "Controller" // The artemis address of the node named here will be used as the networkMapAddress on all other nodes. + node { + name "Controller" + dirName "controller" + nearestCity "London" + advertisedServices = [ "corda.notary.validating" ] + artemisPort 12345 + webPort 12346 + cordapps [] + } + node { + name "NodeA" + dirName "nodea" + nearestCity "London" + advertisedServices = [] + artemisPort 31337 + webPort 31339 + cordapps [] + } + node { + name "NodeB" + dirName "nodeb" + nearestCity "New York" + advertisedServices = [] + artemisPort 31338 + webPort 31340 + cordapps [] + } + } + +You can create more configurations with new tasks that extend Cordform. + +New nodes can be added by simply adding another node block and giving it a different name, directory and ports. When you +run this task it will install the nodes to the directory specified and a script will be generated (for UNIX users only +at present) to run the nodes with one command. + +Other cordapps can also be specified if they are already specified as classpath or compile dependencies in your +``build.gradle``. diff --git a/docs/build/html/_sources/data-model.txt b/docs/build/html/_sources/data-model.txt new file mode 100644 index 0000000000..0ba274072d --- /dev/null +++ b/docs/build/html/_sources/data-model.txt @@ -0,0 +1,278 @@ +Data model +========== + +This article covers the data model: how *states*, *transactions* and *code contracts* interact with each other and +how they are represented in software. It doesn't attempt to give detailed design rationales or information on future +design elements: please refer to the R3 wiki for background information. + +Overview +-------- + +We begin with the idea of a global ledger. In our model although the ledger is shared, it is not always the case that +transactions and ledger entries are globally visible. In cases where a set of transactions stays within a small subgroup of +users it should be possible to keep the relevant data purely within that group. + +To ensure consistency in a global, shared system where not all data may be visible to all participants, we rely +heavily on secure hashes like SHA-256 to identify things. The ledger is defined as a set of immutable **states**, which +are created and destroyed by digitally signed **transactions**. Each transaction points to a set of states that it will +consume/destroy, these are called **inputs**, and contains a set of new states that it will create, these are called +**outputs**. + +States contain arbitrary data, but they always contain at minimum a hash of the bytecode of a +**contract code** file, which is a program expressed in JVM byte code that runs sandboxed inside a Java virtual machine. +Contract code (or just "contracts" in the rest of this document) are globally shared pieces of business logic. + +.. note:: In the current code dynamic loading of contracts is not implemented, so states currently point at + statically created object instances. This will change in the near future. + +Contracts define a **verify function**, which is a pure function given the entire transaction as input. To be considered +valid, the transaction must be **accepted** by the verify function of every contract pointed to by the input and output +states. + +Beyond inputs and outputs, transactions may also contain **commands**, small data packets that +the platform does not interpret itself but which can parameterise execution of the contracts. They can be thought of as +arguments to the verify function. Each command has a list of **public keys** associated with it. The platform ensures +that the transaction is signed by every key listed in the commands before the contracts start to execute. Thus, a verify +function can trust that all listed keys have signed the transaction but is responsible for verifying that any keys required +for the transaction to be valid from the verify function's perspective are included in the list. Public keys +may be random/identityless for privacy, or linked to a well known legal identity, for example via a +*public key infrastructure* (PKI). + +.. note:: Linkage of keys with identities via a PKI is only partially implemented in the current code. + +Commands are always embedded inside a transaction. Sometimes, there's a larger piece of data that can be reused across +many different transactions. For this use case, we have **attachments**. Every transaction can refer to zero or more +attachments by hash. Attachments are always ZIP/JAR files, which may contain arbitrary content. These files are +then exposed on the classpath and so can be opened by contract code in the same manner as any JAR resources +would be loaded. + +.. note:: Attachments must be opened explicitly in the current code. + +Note that there is nothing that explicitly binds together specific inputs, outputs, commands or attachments. Instead +it's up to the contract code to interpret the pieces inside the transaction and ensure they fit together correctly. This +is done to maximise flexibility for the contract developer. + +Transactions may sometimes need to provide a contract with data from the outside world. Examples may include stock +prices, facts about events or the statuses of legal entities (e.g. bankruptcy), and so on. The providers of such +facts are called **oracles** and they provide facts to the ledger by signing transactions that contain commands they +recognise, or by creating signed attachments. The commands contain the fact and the signature shows agreement to that fact. + +Time is also modelled as a fact, with the signature of a special kind of service called a **notary**. A notary is +a (very likely) decentralised service which fulfils the role that miners play in other blockchain systems: +notaries ensure only one transaction can consume any given output. Additionally they may verify a **timestamping +command** placed inside the transaction, which specifies a time window in which the transaction is considered +valid for notarisation. The time window can be open ended (i.e. with a start but no end or vice versa). In this +way transactions can be linked to the notary's clock. + +It is possible for a single Corda network to have multiple competing notaries. Each state points to the notary that +controls it. Whilst a single transaction may only consume states if they are all controlled by the same notary, +a special type of transaction is provided that moves a state (or set of states) from one notary to another. + +.. note:: Currently the platform code will not re-assign states to a single notary as needed for you, in case of + a mismatch. This is a future planned feature. + +As the same terminology often crops up in different distributed ledger designs, let's compare this to other +systems you may be familiar with. You can find more detailed design rationales for why the platform +differs from existing systems in `the R3 wiki `_, +but to summarise, the driving factors are: + +* Improved contract flexibility vs Bitcoin +* Improved scalability vs Ethereum, as well as ability to keep parts of the transaction graph private (yet still uniquely addressable) +* No reliance on proof of work +* Re-use of existing sandboxing virtual machines +* Use of type safe GCd implementation languages +* Simplified auditing + +Comparison with Bitcoin +----------------------- + +Similarities: + +* The basic notion of immutable states that are consumed and created by transactions is the same. +* The notion of transactions having multiple inputs and outputs is the same. Bitcoin sometimes refers to the ledger + as the unspent transaction output set (UTXO set) as a result. +* Like in Bitcoin, a contract is pure function. Contracts do not have storage or the ability to interact with anything. + Given the same transaction, a contract's accept function always yields exactly the same result. +* Bitcoin output scripts are parameterised by the input scripts in the spending transaction. This is somewhat similar + to our notion of a *command*. +* Bitcoin has a global distributed notary service; that's the famous block chain. However, there is only one. Whilst + there is a notion of a "side chain", this isn't integrated with the core Bitcoin data model and thus adds large + amounts of additional complexity meaning in practice side chains are not used. +* Bitcoin transactions, like ours, refer to the states they consume by using a (txhash, index) pair. The Bitcoin + protocol calls these "outpoints". In our code they are known as ``StateRefs`` but the concept is identical. +* Bitcoin transactions have an associated timestamp (the time at which they are mined). + +Differences: + +* A Bitcoin transaction has a single, rigid data format. A "state" in Bitcoin is always a (quantity of bitcoin, script) + pair and cannot hold any other data. Some people have been known to try and hack around this limitation by embedding + data in semi-standardised places in the contract code so the data can be extracted through pattern matching, but this + is a poor approach. Our states can include arbitrary typed data. +* A Bitcoin transaction's acceptance is controlled only by the contract code in the consumed input states. In practice + this has proved limiting. Our transactions invoke not only input contracts but also the contracts of the outputs. +* A Bitcoin script can only be given a fixed set of byte arrays as the input. This means there's no way for a contract + to examine the structure of the entire transaction, which severely limits what contracts can do. +* Our contracts are Turing-complete and can be written in any ordinary programming language that targets the JVM. +* Our transactions and contracts get their time from an attached timestamp rather than a block. This is + important given that we use block-free conflict resolution algorithms. The timestamp can be arbitrarily precise. +* We use the term "contract" to refer to a bundle of business logic that may handle various different tasks, beyond + transaction verification. For instance, currently our contracts also include code for creating valid transactions + (this is often called "wallet code" in Bitcoin). + +Comparison with Ethereum +------------------------ + +Similarities: + +* Like Ethereum, code runs inside a relatively powerful virtual machine and can contain complex logic. Non-assembly + based programming languages can be used for contract programming. +* They are both intended for the modelling of many different kinds of financial contract. + +Differences: + +* The term "contract" in Ethereum refers to an *instantiation* of a program that is replicated and maintained by + every participating node. This instantiation is very much like an object in an OO program: it can receive and send + messages, update local storage and so on. In contrast, we use the term "contract" to refer to a set of functions, only + one of which is a part of keeping the system synchronised (the verify function). That function is pure and + stateless i.e. it may not interact with any other part of the system whilst executing. +* There is no notion of an "account", as there is in Ethereum. +* As contracts don't have any kind of mutable storage, there is no notion of a "message" as in Ethereum. +* Ethereum claims to be a platform not only for financial logic, but literally any kind of application at all. Our + platform considers non-financial applications to be out of scope. + +Rationale for and tradeoffs in adopting a UTXO-style model +---------------------------------------------------------- + +As discussed above, Corda uses the so-called "UTXO set" model (unspent transaction output). In this model, the database +does not track accounts or balances. Instead all database entries are immutable. An entry is either spent or not spent +but it cannot be changed. In Bitcoin, spentness is implemented simply as deletion – the inputs of an accepted transaction +are deleted and the outputs created. + +This approach has some advantages and some disadvantages, which is why some platforms like Ethereum have tried +(or are trying) to abstract this choice away and support a more traditional account-like model. We have explicitly +chosen *not* to do this and our decision to adopt a UTXO-style model is a deliberate one. In the section below, +the rationale for this decision and its pros and cons of this choice are outlined. + +Rationale +--------- + +Corda, in common with other blockchain-like platforms, is designed to bring parties to shared sets of data into +consensus as to the existence, content and allowable evolutions of those data sets. However, Corda is designed with the +explicit aim of avoiding, to the extent possible, the scalability and privacy implications that arise from those platforms' +decisions to adopt a global broadcast model. + +Whilst the privacy implications of a global consensus model are easy to understand, the scalability implications are +perhaps more subtle, yet serious. In a consensus system, it is critical that all processors of a transaction reach +precisely the same conclusion as to its effects. In situations where two transactions may act on the same data set, +it means that the two transactions must be processed in the same *order* by all nodes. If this were not the case then it +would be possible to devise situations where nodes processed transactions in different orders and reached different +conclusions as to the state of the system. It is for this reason that systems like Ethereum effectively run +single-threaded, meaning the speed of the system is limited by the single-threaded performance of the slowest +machine on the network. + +In Corda, we assume the data being processed represents financial agreements between identifiable parties and that these +institutions will adopt the system only if a significant number of such agreements can be managed by the platform. +As such, the system has to be able to support parallelisation of execution to the greatest extent possible, +whilst ensuring correct transaction ordering when two transactions seek to act on the same piece of shared state. + +To achieve this, we must minimise the number of parties who need to receive and process copies of any given +transaction and we must minimise the extent to which two transactions seek to mutate (or supersede) any given piece +of shared state. + +A key design decision, therefore, is what should be the most atomic unit of shared data in the system. This decision +also has profound privacy implications: the more coarsely defined the shared data units, the larger the set of +actors who will likely have a stake in its accuracy and who must process and observe any update to it. + +This becomes most obvious when we consider two models for representing cash balances and payments. + +A simple account model for cash would define a data structure that maintained a balance at a particular bank for each +"account holder". Every holder of a balance would need a copy of this structure and would thus need to process and +validate every payment transaction, learning about everybody else's payments and balances in the process. +All payments across that set of accounts would have to be single-threaded across the platform, limiting maximum +throughput. + +A more sophisticated example might create a data structure per account holder. +But, even here, I would leak my account balance to anybody to whom I ever made +a payment and I could only ever make one payment at a time, for the same reasons above. + +A UTXO model would define a data structure that represented an *instance* of a claim against the bank. An account +holder could hold *many* such instances, the aggregate of which would reveal their balance at that institution. However, +the account holder now only needs to reveal to their payee those instances consumed in making a payment to that payee. +This also means the payer could make several payments in parallel. A downside is that the model is harder to understand. +However, we consider the privacy and scalability advantages to overwhelm the modest additional cognitive load this places +on those attempting to learn the system. + +In what follows, further advantages and disadvantages of this design decision are explored. + +Pros +---- + +The UTXO model has these advantages: + +* Immutable ledger entries gives the usual advantages that a more functional approach brings: it's easy to do analysis + on a static snapshot of the data and reason about the contents. +* Because there are no accounts, it's very easy to apply transactions in parallel even for high traffic legal entities + assuming sufficiently granular entries. +* Transaction ordering becomes trivial: it is impossible to mis-order transactions due to the reliance on hash functions + to identify previous states. There is no need for sequence numbers or other things that are hard to provide in a + fully distributed system. +* Conflict resolution boils down to the double spending problem, which places extremely minimal demands on consensus + algorithms (as the variable you're trying to reach consensus on is a set of booleans). + +Cons +---- + +It also comes with some pretty serious complexities that in practice must be abstracted from developers: + +* Representing numeric amounts using immutable entries is unnatural. For instance, if you receive $1000 and wish + to send someone $100, you have to consume the $1000 output and then create two more: a $100 for the recipient and + $900 back to yourself as change. The fact that this happens can leak private information to an observer. +* Because users do need to think in terms of balances and statements, you have to layer this on top of the + underlying ledger: you can't just read someone's balance out of the system. Hence, the "wallet" / position manager. + Experience from those who have developed wallets for Bitcoin and other systems is that they can be complex pieces of code, + although the bulk of wallets' complexity in public systems is handling the lack of finality (and key management). +* Whilst transactions can be applied in parallel, it is much harder to create them in parallel due to the need to + strictly enforce a total ordering. + +With respect to parallel creation, if the user is single threaded this is fine, but in a more complex situation +where you might want to be preparing multiple transactions in flight this can prove a limitation – in +the worst case where you have a single output that represents all your value, this forces you to serialise +the creation of every transaction. If transactions can be created and signed very fast that's not a concern. +If there's only a single user, that's not a concern. + +Both cases are typically true in the Bitcoin world, so users don't suffer from this much. In the context of a +complex business with a large pool of shared funds, in which creation of transactions may be very slow due to the +need to get different humans to approve a tx using a signing device, this could quickly lead to frustrating +conflicts where someone approves a transaction and then discovers that it has become a double spend and +they must sign again. In the absolute worst case you could get a form of human livelock. + +The tricky part about solving these problems is that the simplest way to express a payment request +("send me $1000 to public key X") inherently results in you receiving a single output, which then can +prove insufficiently granular to be convenient. In the Bitcoin space Mike Hearn and Gavin Andresen designed "BIP 70" +to solve this: it's a simple binary format for requesting a payment and specifying exactly how you'd like to get paid, +including things like the shape of the transaction. It may seem that it's an over complex approach: could you not +just immediately respend the big output back to yourself in order to split it? And yes, you could, until you hit +scenarios like "the machine requesting the payment doesn't have the keys needed to spend it", +which turn out to be very common. So it's really more effective for a recipient to be able to say to the +sender, "here's the kind of transaction I want you to send me". The :doc:`protocol framework ` +may provide a vehicle to make such negotiations simpler. + +A further challenge is privacy. Whilst our goal of not sending transactions to nodes that don't "need to know" +helps, to verify a transaction you still need to verify all its dependencies and that can result in you receiving +lots of transactions that involve random third parties. The problems start when you have received lots of separate +payments and been careful not to make them linkable to your identity, but then you need to combine them all in a +single transaction to make a payment. + +Mike Hearn wrote an article about this problem and techniques to minimise it in +`this article `_ from 2013. This article +coined the term "merge avoidance", which has never been implemented in the Bitcoin space, +although not due to lack of practicality. + +A piece of future work for the wallet implementation will be to implement automated "grooming" of the wallet +to "reshape" outputs to useful/standardised sizes, for example, and to send outputs of complex transactions +back to their issuers for reissuance to "sever" long privacy-breaching chains. + +Finally, it should be noted that some of the issues described here are not really "cons" of +the UTXO model; they're just fundamental. If you used many different anonymous accounts to preserve some privacy +and then needed to spend the contents of them all simultaneously, you'd hit the same problem, so it's not +something that can be trivially fixed with data model changes. diff --git a/docs/build/html/_sources/event-scheduling.txt b/docs/build/html/_sources/event-scheduling.txt new file mode 100644 index 0000000000..94ed2b2189 --- /dev/null +++ b/docs/build/html/_sources/event-scheduling.txt @@ -0,0 +1,102 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Event scheduling +================ + +This article explains our approach to modelling time based events in code. It explains how a contract +state can expose an upcoming event and what action to take if the scheduled time for that event is reached. + +Introduction +------------ + +Many financial instruments have time sensitive components to them. For example, an Interest Rate Swap has a schedule +for when: + +* Interest rate fixings should take place for floating legs, so that the interest rate used as the basis for payments + can be agreed. +* Any payments between the parties are expected to take place. +* Any payments between the parties become overdue. + +Each of these is dependent on the current state of the financial instrument. What payments and interest rate fixings +have already happened should already be recorded in the state, for example. This means that the *next* time sensitive +event is thus a property of the current contract state. By next, we mean earliest in chronological terms, that is still +due. If a contract state is consumed in the UTXO model, then what *was* the next event becomes irrelevant and obsolete +and the next time sensitive event is determined by any successor contract state. + +Knowing when the next time sensitive event is due to occur is useful, but typically some *activity* is expected to take +place when this event occurs. We already have a model for business processes in the form of :doc:`protocols `, +so in the platform we have introduced the concept of *scheduled activities* that can invoke protocol state machines +at a scheduled time. A contract state can optionally described the next scheduled activity for itself. If it omits +to do so, then nothing will be scheduled. + +How to implement scheduled events +--------------------------------- + +There are two main steps to implementing scheduled events: + +* Have your ``ContractState`` implementation also implement ``SchedulableState``. This requires a method named + ``nextScheduledActivity`` to be implemented which returns an optional ``ScheduledActivity`` instance. + ``ScheduledActivity`` captures what ``ProtocolLogic`` instance each node will run, to perform the activity, and when it + will run is described by a ``java.time.Instant``. Once your state implements this interface and is tracked by the + wallet, it can expect to be queried for the next activity when committed to the wallet. +* If nothing suitable exists, implement a ``ProtocolLogic`` to be executed by each node as the activity itself. + The important thing to remember is that in the current implementation, each node that is party to the transaction + will execute the same ``ProtocolLogic``, so it needs to establish roles in the business process based on the contract + state and the node it is running on. Each side will follow different but complementary paths through the business logic. + +.. note:: The scheduler's clock always operates in the UTC time zone for uniformity, so any time zone logic must be + performed by the contract, using ``ZonedDateTime``. + +In the short term, until we have automatic protocol session set up, you will also likely need to install a network +handler to help with obtaining a unqiue and secure random session. An example is described below. + +The production and consumption of ``ContractStates`` is observed by the scheduler and the activities associated with +any consumed states are unscheduled. Any newly produced states are then queried via the ``nextScheduledActivity`` +method and if they do not return ``null`` then that activity is scheduled based on the content of the +``ScheduledActivity`` object returned. Be aware that this *only* happens if the wallet considers the state +"relevant", for instance, because the owner of the node also owns that state. States that your node happens to +encounter but which aren't related to yourself will not have any activities scheduled. + +An example +---------- + +Let's take an example of the interest rate swap fixings for our scheduled events. The first task is to implement the +``nextScheduledActivity`` method on the ``State``. + + +.. container:: codeset + + .. sourcecode:: kotlin + + override fun nextScheduledActivity(thisStateRef: StateRef, + protocolLogicRefFactory: ProtocolLogicRefFactory): ScheduledActivity? { + val nextFixingOf = nextFixingOf() ?: return null + + val (instant, duration) = suggestInterestRateAnnouncementTimeWindow(index = nextFixingOf.name, + source = floatingLeg.indexSource, + date = nextFixingOf.forDay) + return ScheduledActivity(protocolLogicRefFactory.create(TwoPartyDealProtocol.FixingRoleDecider::class.java, + thisStateRef, duration), instant) + } + +The first thing this does is establish if there are any remaining fixings. If there are none, then it returns ``null`` +to indicate that there is no activity to schedule. Otherwise it calculates the ``Instant`` at which the interest rate +should become available and schedules an activity at that time to work out what roles each node will take in the fixing +business process and to take on those roles. That ``ProtocolLogic`` will be handed the ``StateRef`` for the interest +rate swap ``State`` in question, as well as a tolerance ``Duration`` of how long to wait after the activity is triggered +for the interest rate before indicating an error. + +.. note:: This is a way to create a reference to the ProtocolLogic class and its constructor parameters to + instantiate. The reference can be checked against a per-node whitelist of approved and allowable types as + part of our overall security sandboxing. + + +As previously mentioned, we currently need a small network handler to assist with session setup until the work to +automate that is complete. See the interest rate swap specific implementation ``FixingSessionInitiationHandler`` which +is responsible for starting a ``ProtocolLogic`` to perform one role in the fixing protocol with the ``sessionID`` sent +by the ``FixingRoleDecider`` on the other node which then launches the other role in the fixing protocol. Currently +the handler needs to be manually installed in the node. diff --git a/docs/build/html/_sources/getting-set-up.txt b/docs/build/html/_sources/getting-set-up.txt new file mode 100644 index 0000000000..656576c5b2 --- /dev/null +++ b/docs/build/html/_sources/getting-set-up.txt @@ -0,0 +1,61 @@ +Getting set up +============== + +Ensure that you have access to R3 git repository. + + https://bitbucket.org/R3-CEV/r3prototyping.git + +If you cannot access the page please contact the R3 admin team. + +Install the Oracle JDK 8u45 or higher. OpenJDK will probably also work, but it hasn't been tested. + +Then install IntelliJ. The Community Edition is good enough: + + https://www.jetbrains.com/idea/download/ + +Upgrade the Kotlin plugin to the latest version by clicking "Configure > Plugins" in the opening screen, +then clicking "Install JetBrains plugin", then searching for Kotlin, then hitting "Upgrade" and then "Restart". +You can confirm what is the latest version of Kotlin plugin on this page: + + https://plugins.jetbrains.com/plugin/6954 + +Choose "Check out from version control" and use this git URL. Please remember to replace your_username with your +actual bitbucket user name. + + https://your_username@bitbucket.org/R3-CEV/r3prototyping.git + +After code is cloned open the project. Please ensure that Gradle project is imported. +You should have the "Unliked Gradle project?" pop-up window in the IntelliJ top right corner. Please click on "Import Gradle Project". Wait for it to think and download the dependencies. After that you might have another popup titled "Unindexed remote maven repositories found." This is general IntelliJ question and doesn't affect Corda, therefore you can decided to index them or not. + +Next click on "green arrow" next to "All tests" pop-up on the top toolbar. + +The code should build, the unit tests should show as all green. + +You can catch up with the latest code by selecting "VCS -> Update Project" in the menu. + +If IntelliJ complains about lack of an SDK +------------------------------------------ + +If on attempting to open the project (including importing Gradle project), IntelliJ refuses because SDK was not selected, do the following: + + Configure -> Project Defaults -> Project Structure + +on that tab: + + Project Settings / Project + +click on New… next to the red symbol, and select JDK. It should then pop up and show the latest JDK it has +found at something like + + jdk1.8.0_xx…/Contents/Home + +Also select Project language level: as 8. Click OK. Open should now work. + +Doing it without IntelliJ +------------------------- + +If you don't want to explore or modify the code in a local IDE, you can also just use the command line and a text editor: +* First run ``git clone https://your_username@bitbucket.org/R3-CEV/r3prototyping.git`` to download Corda source code. Please remember to replace your_username with your actual bitbucket user name. +* Next ensure that you are in r3repository ``cd r3repository`` +* Then you can run ``./gradlew test`` to run the unit tests. +* Finally remeber to run ``git pull`` to upgrade the source code. diff --git a/docs/build/html/_sources/index.txt b/docs/build/html/_sources/index.txt new file mode 100644 index 0000000000..ca54315def --- /dev/null +++ b/docs/build/html/_sources/index.txt @@ -0,0 +1,78 @@ +Welcome to the Corda! +===================== + +.. warning:: This build of the docs is from the *master branch*, not a milestone release. It may not reflect the + current state of the code. + +This is the developer guide for Corda, a proposed architecture for distributed ledgers. Here are the sources +of documentation you may find useful, from highest level to lowest: + +1. The `Introductory white paper`_ describes the motivating vision and background of the project. It is the kind + of document your boss should read. It describes why the project exists and briefly compares it to alternative + systems on the market. +2. This user guide. It describes *how* to use the system to write apps. It assumes you already have read the + relevant sections of the technology white paper and now wish to learn how to use it. +3. The `API docs`_. + +.. _`Introductory white paper`: _static/corda-introductory-whitepaper.pdf +.. _`Technical white paper`: _static/corda-technical-whitepaper.pdf +.. _`API docs`: api/index.html + +Read on to learn: + +.. toctree:: + :maxdepth: 2 + :caption: Overview + + inthebox + getting-set-up + data-model + transaction-data-types + merkle-trees + consensus + messaging + persistence + creating-a-cordapp + running-the-demos + node-administration + corda-configuration-files + +.. toctree:: + :maxdepth: 2 + :caption: Tutorials + + where-to-start + tutorial-contract + tutorial-contract-clauses + tutorial-test-dsl + tutorial-clientrpc-api + protocol-state-machines + oracles + tutorial-attachments + event-scheduling + +.. toctree:: + :maxdepth: 2 + :caption: Contracts + + contract-catalogue + contract-irs + initialmarginagreement + +.. toctree:: + :maxdepth: 2 + :caption: Node API + + clientrpc + +.. toctree:: + :maxdepth: 2 + :caption: Appendix + + secure-coding-guidelines + release-process + release-notes + network-simulator + node-explorer + codestyle + building-the-docs diff --git a/docs/build/html/_sources/initialmarginagreement.txt b/docs/build/html/_sources/initialmarginagreement.txt new file mode 100644 index 0000000000..d18a3105da --- /dev/null +++ b/docs/build/html/_sources/initialmarginagreement.txt @@ -0,0 +1,73 @@ +Initial Margin Agreements +========================= + +This app is a demonstration of how Corda can be used for the real world requirement of initial margin calculation and +agreement; featuring the integration of complex and industry proven third party libraries into Corda nodes. + +SIMM Introduction +----------------- + +SIMM is an acronym for "Standard Initial Margin Model". It is effectively the calculation of a "margin" that is paid +by one party to another when they agree a trade on certain types of transaction. This margin is +paid such that, in the event of one of the counterparties suffering a credit event +(a financial term and a polite way to say defaulting, not paying the debts that are due, or potentially even bankruptcy), +then the party that is owed any sum already has some of the amount that it should have been paid. This payment to the +receiving party is a preventative measure in order to reduce the risk of a potentially catastrophic default domino +effect that caused the `Great Financial Crisis `_, +as it means that they can be assured that if they need to pay another party, they will have a proportion of the funds +that they have been relying on. + +To enact this, in September 2016, the ISDA committee - with full backing from various governing bodies - +`issued a ruling on what is known as the ISDA SIMM ™ model `_, +a way of fairly and consistently calculating this margin. Any parties wishing to trade a financial product that is +covered under this ruling would, independently, use this model and calculate their margin payment requirement, +agree it with their trading counterparty and then pay (or receive, depending on the results of this calculation) +this amount. In the case of disagreement that is not resolved in a timely fashion, this payment would increase +and so therefore it is in the parties interest to reach agreement in a short as time frame as possible. + +To be more accurate, the SIMM calculation is not performed on just one trade - it is calculated on an aggregate of +intermediary values (which in this model are sensitivities to risk factors) from a portfolio of trades; therefore +the input to a SIMM is actually this data, not the individual trades itself. + +Also note that implementations of the SIMM are actually protected and subject to license restrictions by ISDA +(this is due to the model itself being protected). We were fortunate enough to technically partner with +`OpenGamma `_ who allowed us to demonstrate the SIMM process using their proprietary model. +In the source code released, we have replaced their analytics engine with very simple stub functions that allow +the process to run and can easily be swapped out in place for their real libraries. + +Process steps +------------- + +Preliminaries + - Ensure that there are a number of live trades with another party financial products that are covered under the + ISDA SIMM agreement (if none, then use the demo to enter some simple trades as described below). + +Initial Margin Agreement Process + - Agree that one will be performing the margining calculation against a portfolio of trades with another party, and agree the trades in that portfolio. In practice, one node will start the protocol but it does not matter which node does. + - Individually (at the node level), identify the data (static, reference etc) one will need in order to be able to calculate the metrics on those trades + - Confirm with the other counterparty the dataset from the above set + - Calculate any intermediary steps and values needed for the margin calculation (ie sensitivities to risk factors) + - Agree on the results of these steps + - Calculate the initial margin + - Agree on the calculation of the above with the other party + - In practice, pay (or receive) this margin (omitted for the sake of complexity for this example) + + +Running the app +--------------- + +The demonstration can be run in two ways - via IntelliJ (which will allow you to add breakpoints, debug, etc), or via gradle and the command line. + +Run with IntelliJ:: + + 1. Open the `cordapp-samples` project with IntelliJ + 2. Run the shared run configuration "SIMM Valuation Demo" + 3. Browse to http://localhost:10005/web/simmvaluationdemo + +Run via CLI:: + + 1. Navigate to the `cordapp-samples` directory in your shell + 2. Run the gradle target `deployNodes` (ie; ./gradlew deployNodes for Unix or gradlew.bat on Windows) + 1. Unix: `cd simm-valuation-demo/build/nodes && ./runnodes`. + 2. Windows: Open a command line window in each subdirectory of `simm-valuation-demo/build/nodes` and run `java -jar corda.jar` + 4. Browse to http://localhost:10005/web/simmvaluationdemo diff --git a/docs/build/html/_sources/inthebox.txt b/docs/build/html/_sources/inthebox.txt new file mode 100644 index 0000000000..3d2bf3b8b9 --- /dev/null +++ b/docs/build/html/_sources/inthebox.txt @@ -0,0 +1,41 @@ +What's included? +================ + +The Corda prototype currently includes: + +* A peer to peer network with message persistence and delivery retries. +* Key data structures for defining contracts and states. +* Smart contracts, which you can find in the :doc:`contract-catalogue`. +* Algorithms that work with them, such as serialising, hashing, signing, and verification of the signatures. +* API documentation and tutorials (what you're reading). +* A business process orchestration framework. +* Notary infrastructure for precise timestamping, and elimination of double spending without a blockchain. +* A simple REST API, and a web app demo that uses it to present a frontend for IRS trading. + +Some things it does not currently include but should gain later are: + +* Sandboxing, distribution or publication of smart contract code +* A user interface for administration + +The prototype's goal is rapid exploration of ideas. Therefore in places it takes shortcuts that a production system +would not in order to boost productivity: + +* It uses an object graph serialization framework instead of a well specified, vendor neutral protocol. +* There's currently no permissioning framework. +* Some privacy techniques aren't implemented yet. +* It uses an embedded SQL database and doesn't yet have connectivity support for mainstream SQL vendors (Oracle, + Postgres, MySQL, SQL Server etc). + +Kotlin +------ + +Corda is written in a language called `Kotlin `_. Kotlin is a language that targets the JVM +and can be thought of as a simpler Scala, with much better Java interop. It is developed by and has commercial support +from JetBrains, the makers of the IntelliJ IDE and other popular developer tools. + +As Kotlin is very new, without a doubt you have not encountered it before. Don't worry: it is designed as a better +Java for industrial use and as such, the syntax was carefully designed to be readable even to people who don't know +the language, after only a few minutes of introduction. + +Due to the seamless Java interop the use of Kotlin to extend the platform is *not* required and the tutorial shows how +to write contracts in both Kotlin and Java. You can `read more about why Kotlin is a potentially strong successor to Java here `_. \ No newline at end of file diff --git a/docs/build/html/_sources/merkle-trees.txt b/docs/build/html/_sources/merkle-trees.txt new file mode 100644 index 0000000000..1b30b68df3 --- /dev/null +++ b/docs/build/html/_sources/merkle-trees.txt @@ -0,0 +1,111 @@ +Transaction Tear-offs +====================== + +One of the basic data structures in our platform is a transaction. It can be passed around to be signed and verified, +also by third parties. The construction of transactions assumes that they form a whole entity with input and output states, +commands and attachments inside. However all sensitive data shouldn’t be revealed to other nodes that take part in +the creation of transaction on validation level (a good example of this situation is the Oracle which validates only +embedded commands). How to achive it in a way that convinces the other party the data they got for signing really did form +a part of the transaction? + +We decided to use well known and described cryptographic scheme to provide proofs of inclusion and data integrity. +Merkle trees are widely used in peer-to-peer networks, blockchain systems and git. +You can read more on the concept `here `_. + +Merkle trees in Corda +---------------------- + +Transactions are split into leaves, each of them contains either input, output, command or attachment. Other fields like +timestamp or signers are not used in the calculation. +Next, the Merkle tree is built in the normal way by hashing the concatenation +of nodes’ hashes below the current one together. It’s visible on the example image below, where ``H`` denotes sha256 function, +"+" - concatenation. + +.. image:: resources/merkleTree.png + +The transaction has one input state, one output and three commands. If a tree is not a full binary tree, the rightmost nodes are +duplicated in hash calculation (dotted lines). + +Finally, the hash of the root is the identifier of the transaction, it's also used for signing and verification of data integrity. +Every change in transaction on a leaf level will change its identifier. + +Hiding data +----------- + +Hiding data and providing the proof that it formed a part of a transaction is done by constructing Partial Merkle Trees +(or Merkle branches). A Merkle branch is a set of hashes, that given the leaves’ data, is used to calculate the root’s hash. +Then that hash is compared with the hash of a whole transaction and if they match it means that data we obtained belongs +to that particular transaction. + +.. image:: resources/partialMerkle.png + +In the example above, the red node is the one holding data for signing Oracle service. Blue nodes' hashes form the Partial Merkle +Tree, dotted ones are not included. Having the command that should be in a red node place and branch we are able to calculate +root of this tree and compare it with original transaction identifier - we have a proof that this command belongs to this transaction. + +Example of usage +----------------- + +Let’s focus on a code example. We want to construct a transaction with commands containing interest rate fix data as in: +:doc:`oracles`. +After construction of a partial transaction, with included ``Fix`` commands in it, we want to send it to the Oracle for checking +and signing. To do so we need to specify which parts of the transaction are going to be revealed. That can be done by constructing +filtering functions for inputs, outputs, attachments and commands separately. If a function is not provided by default none +of the elements from this group will be included in a Partial Merkle Tree. + +.. container:: codeset + + .. sourcecode:: kotlin + + val partialTx = ... + val oracle: Party = ... + fun filterCommands(c: Command) = oracle.owningKey in c.signers && c.value is Fix + val filterFuns = FilterFuns(filterCommands = ::filterCommands) + +Assuming that we already assembled partialTx with some commands and know the identity of Oracle service, +we pass filtering function over commands - ``filterCommands`` to ``FilterFuns``. It filters only +commands of type ``Fix`` as in IRSDemo example. Then we can construct ``FilteredTransaction``: + +.. container:: codeset + + .. sourcecode:: kotlin + + val wtx: WireTransaction = partialTx.toWireTransaction() + val ftx = FilteredTransaction.buildMerkleTransaction(wtx, filterFuns) + +In the Oracle example this step takes place in ``RatesFixProtocol``: + +.. container:: codeset + + .. sourcecode:: kotlin + + val protocol = RatesFixProtocol(partialTx, filterFuns, oracle, fixOf, "0.675".bd, "0.1".bd) + +``FilteredTransaction`` holds ``filteredLeaves`` (data that we wanted to reveal) and Merkle branch for them. + +.. container:: codeset + + .. sourcecode:: kotlin + + // Getting included commands, inputs, outputs, attachments. + val cmds: List = ftx.filteredLeaves.commands + val ins: List = ftx.filteredLeaves.inputs + val outs: List> = ftx.filteredLeaves.outputs + val attchs: List = ftx.filteredLeaves.attachments + + +If you want to verify obtained ``FilteredTransaction`` all you need is the root hash of the full transaction: + +.. container:: codeset + + .. sourcecode:: kotlin + + if (!ftx.verify(merkleRoot)){ + throw MerkleTreeException("Rate Fix Oracle: Couldn't verify partial Merkle tree.") + } + + +.. note:: The way the ``FilteredTransaction`` is constructed ensures that after signing of the root hash it's impossible to add or remove + leaves. However, it can happen that having transaction with multiple commands one party reveals only subset of them to the Oracle. + As signing is done now over the merkle root hash, the service signs all commands of given type, even though it didn't see + all of them. This issue will be handled after implementing partial signatures. diff --git a/docs/build/html/_sources/messaging.txt b/docs/build/html/_sources/messaging.txt new file mode 100644 index 0000000000..74cfabd871 --- /dev/null +++ b/docs/build/html/_sources/messaging.txt @@ -0,0 +1,49 @@ +Networking and messaging +======================== + +Corda uses AMQP/1.0 over TLS between nodes which is currently implemented using Apache Artemis, an embeddable message +queue broker. Building on established MQ protocols gives us features like persistence to disk, automatic delivery +retries with backoff and dead-letter routing, security, large message streaming and so on. + +Artemis is hidden behind a thin interface that also has an in-memory only implementation suitable for use in +unit tests and visualisation tools. + +.. note:: A future version of Corda will allow the MQ broker to be split out of the main node and run as a + separate server. We may also support non-Artemis implementations via JMS, allowing the broker to be swapped + out for alternative implementations. + +There are multiple ways of interacting with the network. When writing an application you typically won't use the +messaging subsystem directly. Instead you will build on top of the :doc:`protocol framework `, +which adds a layer on top of raw messaging to manage multi-step protocols and let you think in terms of identities +rather than specific network endpoints. + +Messaging types +--------------- + +Every ``Message`` object has an associated *topic* and may have a *session ID*. These are wrapped in a ``TopicSession``. +An implementation of ``MessagingService`` can be used to create messages and send them. You can get access to the +messaging service via the ``ServiceHub`` object that is provided to your app. Endpoints on the network are +identified at the lowest level using ``SingleMessageRecipient`` which may be e.g. an IP address, or in future +versions perhaps a routing path through the network. + +Network Map Service +------------------- + +Supporting the messaging layer is a network map service, which is responsible for tracking public nodes on the network. + +Nodes have an internal component, the network map cache, which contains a copy of the network map (which is just a +document). When a node starts up its cache fetches a copy of the full network map, and requests to be notified of +changes. The node then registers itself with the network map service, and the service notifies subscribers that a new +node has joined the network. Nodes do not automatically deregister themselves, so (for example) nodes going offline +briefly for maintenance are retained in the network map, and messages for them will be queued, minimising disruption. + +Nodes submit signed changes to the map service, which then forwards update notifications on to nodes which have +requested to be notified of changes. + +The network map currently supports: + +* Looking up nodes by service +* Looking up node for a party +* Suggesting a node providing a specific service, based on suitability for a contract and parties, for example suggesting + an appropriate interest rates oracle for a interest rate swap contract. Currently no recommendation logic is in place. + The code simply picks the first registered node that supports the required service. \ No newline at end of file diff --git a/docs/build/html/_sources/network-simulator.txt b/docs/build/html/_sources/network-simulator.txt new file mode 100644 index 0000000000..93dba16ccb --- /dev/null +++ b/docs/build/html/_sources/network-simulator.txt @@ -0,0 +1,41 @@ +Network Simulator +================= + +A network simulator is provided which shows traffic between nodes through the lifecycle of an interest rate swap +contract. It can optionally also show network setup, during which nodes register themselves with the network +map service and are notified of the changes to the map. The network simulator is run from the command line via Gradle: + +**Windows**:: + + gradlew.bat network-simulator:run + +**Other**:: + + ./gradlew network-simulator:run + +Interface +--------- + +.. image:: network-simulator.png + +The network simulator can be run automatically, or stepped manually through each step of the interest rate swap. The +options on the simulator window are: + +Simulate initialisation + If checked, the nodes registering with the network map is shown. Normally this setup step + is not shown, but may be of interest to understand the details of node discovery. +Run + Runs the network simulation in automatic mode, in which it progresses each step on a timed basis. Once running, + the simulation can be paused in order to manually progress it, or reset. +Next + Manually progress the simulation to the next step. +Reset + Reset the simulation (only available when paused). +Map/Circle + How the nodes are shown, by default nodes are rendered on a world map, but alternatively they can rendered + in a circle layout. + +While the simulation runs, details of the steps currently being executed are shown in a sidebar on the left hand side +of the window. + +.. TODO: Add documentation on how to use with different contracts for testing/debugging diff --git a/docs/build/html/_sources/node-administration.txt b/docs/build/html/_sources/node-administration.txt new file mode 100644 index 0000000000..7cf0211341 --- /dev/null +++ b/docs/build/html/_sources/node-administration.txt @@ -0,0 +1,105 @@ +Node administration +=================== + +When a node is running, it exposes an embedded database server, an embedded web server that lets you monitor it, +you can upload and download attachments, access a REST API and so on. + +Database access +--------------- + +The node exposes its internal database over a socket which can be browsed using any tool that can use JDBC drivers. +The JDBC URL is printed during node startup to the log and will typically look like this: + + ``jdbc:h2:tcp://192.168.0.31:31339/node`` + +The username and password can be altered in the :doc:`corda-config-files` but default to username "sa" and a blank +password. + +Any database browsing tool that supports JDBC can be used, but if you have IntelliJ Ultimate edition then there is +a tool integrated with your IDE. Just open the database window and add an H2 data source with the above details. +You will now be able to browse the tables and row data within them. + +Monitoring your node +-------------------- + +Like most Java servers, the node exports various useful metrics and management operations via the industry-standard +`JMX infrastructure `_. JMX is a standard API +for registering so-called *MBeans* ... objects whose properties and methods are intended for server management. It does +not require any particular network protocol for export. So this data can be exported from the node in various ways: +some monitoring systems provide a "Java Agent", which is essentially a JVM plugin that finds all the MBeans and sends +them out to a statistics collector over the network. For those systems, follow the instructions provided by the vendor. + +Sometimes though, you just want raw access to the data and operations itself. So nodes export them over HTTP on the +``/monitoring/json`` HTTP endpoint, using a program called `Jolokia `_. Jolokia defines the JSON +and REST formats for accessing MBeans, and provides client libraries to work with that protocol as well. + +Here are a few ways to build dashboards and extract monitoring data for a node: + +* `JMX2Graphite `_ is a tool that can be pointed to /monitoring/json and will + scrape the statistics found there, then insert them into the Graphite monitoring tool on a regular basis. It runs + in Docker and can be started with a single command. +* `JMXTrans `_ is another tool for Graphite, this time, it's got its own agent + (JVM plugin) which reads a custom config file and exports only the named data. It's more configurable than + JMX2Graphite and doesn't require a separate process, as the JVM will write directly to Graphite. +* *Java Mission Control* is a desktop app that can connect to a target JVM that has the right command line flags set + (or always, if running locally). You can explore what data is available, create graphs of those metrics, and invoke + management operations like forcing a garbage collection. +* Cloud metrics services like New Relic also understand JMX, typically, by providing their own agent that uploads the + data to their service on a regular schedule. + +Uploading and downloading attachments +------------------------------------- + +Attachments are files that add context to and influence the behaviour of transactions. They are always identified by +hash and they are public, in that they propagate through the network to wherever they are needed. + +All attachments are zip files. Thus to upload a file to the ledger you must first wrap it into a zip (or jar) file. Then +you can upload it by running this command from a UNIX terminal: + +.. sourcecode:: shell + + curl -F myfile=@path/to/my/file.zip http://localhost:31338/upload/attachment + +The attachment will be identified by the SHA-256 hash of the contents, which you can get by doing: + +.. sourcecode:: shell + + shasum -a 256 file.zip + +on a Mac or by using ``sha256sum`` on Linux. Alternatively, the hash will be returned to you when you upload the +attachment. + +An attachment may be downloaded by fetching: + +.. sourcecode:: shell + + http://localhost:31338/attachments/DECD098666B9657314870E192CED0C3519C2C9D395507A238338F8D003929DE9 + +where DECD... is of course replaced with the hash identifier of your own attachment. Because attachments are always +containers, you can also fetch a specific file within the attachment by appending its path, like this: + +.. sourcecode:: shell + + http://localhost:31338/attachments/DECD098666B9657314870E192CED0C3519C2C9D395507A238338F8D003929DE9/path/within/zip.txt + +Uploading interest rate fixes +----------------------------- + +If you would like to operate an interest rate fixing service (oracle), you can upload fix data by uploading data in +a simple text format to the ``/upload/interest-rates`` path on the web server. + +The file looks like this:: + + # Some pretend noddy rate fixes, for the interest rate oracles. + + LIBOR 2016-03-16 1M = 0.678 + LIBOR 2016-03-16 2M = 0.655 + EURIBOR 2016-03-15 1M = 0.123 + EURIBOR 2016-03-15 2M = 0.111 + +The columns are: + +* Name of the fix +* Date of the fix +* The tenor / time to maturity in days +* The interest rate itself \ No newline at end of file diff --git a/docs/build/html/_sources/node-explorer.txt b/docs/build/html/_sources/node-explorer.txt new file mode 100644 index 0000000000..2aa1e44375 --- /dev/null +++ b/docs/build/html/_sources/node-explorer.txt @@ -0,0 +1,70 @@ +Node Explorer +============= + +The node explorer provide views to the node's vault and transaction data using Corda's RPC framework. +The user can execute cash transaction commands to issue and move cash to other party on the network or exit cash using the user interface. + +Running the UI +-------------- +**Windows**:: + + gradlew.bat tools:explorer:run + +**Other**:: + + ./gradlew tools:explorer:run + + +Running Demo Nodes +------------------ +**Windows**:: + + gradlew.bat tools:explorer:runDemoNodes + +**Other**:: + + ./gradlew tools:explorer:runDemoNodes + +.. note:: 3 Corda nodes will be created on the following port on localhost by default. + + * Notary -> 20002 + * Alice -> 20004 + * Bob -> 20006 + +Interface +--------- +Login + User can login to any Corda node using the explorer, alternately, `gradlew explorer:runDemoNodes` can be used to start up demo nodes for testing. + Corda node address, username and password are required for login, the address is defaulted to localhost:0 if leave blank. + Username and password can be configured in node's configuration file; for demo nodes, it is defaulted to ``user1`` and ``test``. +.. note:: If you are connecting to the demo nodes, only Alice and Bob (20004, 20006) are accessible using user1 credential, you won't be able to connect to the notary. + +.. image:: resources/explorer/login.png + :scale: 50 % + :align: center + +Home + Home view shows the top level state of node and vault; currently, it shows your cash balance and the numbers of transaction executed. + The dashboard is intended to house widgets from different CordApp's and provide useful information to system admin at a glance. + +.. image:: resources/explorer/dashboard.png + +Cash + The cash view shows all currencies you currently own in a tree table format, it is grouped by issuer -> currency. + Individual cash transactions can be viewed by clicking on the table row. The user can also use the search field to narrow down the scope. + +.. image:: resources/explorer/vault.png + +Transactions + The transaction view contains all transactions handled by the node in a table view. It shows basic information on the table e.g. Transaction ID, + command type, USD equivalence value etc. User can expand the row by double clicking to view the inputs, + outputs and the signatures details for that transaction. + +.. image:: resources/explorer/transactionView.png + +New Transaction + This is where you can create new transaction; currently only the cash contract is supported. + The user can choose from three transaction types (issue, move and exit) and any party visible on the network. + The result of the transaction will be visible in the transaction screen when executed. + +.. image:: resources/explorer/newTransaction.png diff --git a/docs/build/html/_sources/oracles.txt b/docs/build/html/_sources/oracles.txt new file mode 100644 index 0000000000..06f5843818 --- /dev/null +++ b/docs/build/html/_sources/oracles.txt @@ -0,0 +1,134 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Writing oracle services +======================= + +This article covers *oracles*: network services that link the ledger to the outside world by providing facts that +affect the validity of transactions. + +The current prototype includes an example oracle that provides an interest rate fixing service. It is used by the +IRS trading demo app. + +Introduction +------------ + +Oracles are a key concept in the block chain/decentralised ledger space. They can be essential for many kinds of +application, because we often wish to condition a transaction on some fact being true or false, but the ledger itself +has a design that is essentially functional: all transactions are *pure* and *immutable*. Phrased another way, a +smart contract cannot perform any input/output or depend on any state outside of the transaction itself. There is no +way to download a web page or interact with the user, in a smart contract. It must be this way because everyone must +be able to independently check a transaction and arrive at an identical conclusion for the ledger to maintan its +integrity: if a transaction could evaluate to "valid" on one computer and then "invalid" a few minutes later on a +different computer, the entire shared ledger concept wouldn't work. + +But it is often essential that transactions do depend on data from the outside world, for example, verifying that an +interest rate swap is paying out correctly may require data on interest rates, verifying that a loan has reached +maturity requires knowledge about the current time, knowing which side of a bet receives the payment may require +arbitrary facts about the real world (e.g. the bankruptcy or solvency of a company or country) ... and so on. + +We can solve this problem by introducing services that create digitally signed data structures which assert facts. +These structures can then be used as an input to a transaction and distributed with the transaction data itself. Because +the statements are themselves immutable and signed, it is impossible for an oracle to change its mind later and +invalidate transactions that were previously found to be valid. In contrast, consider what would happen if a contract +could do an HTTP request: it's possible that an answer would change after being downloaded, resulting in loss of +consensus (breaks). + +The two basic approaches +------------------------ + +The architecture provides two ways of implementing oracles with different tradeoffs: + +1. Using commands +2. Using attachments + +When a fact is encoded in a command, it is embedded in the transaction itself. The oracle then acts as a co-signer to +the entire transaction. The oracle's signature is valid only for that transaction, and thus even if a fact (like a +stock price) does not change, every transaction that incorporates that fact must go back to the oracle for signing. + +When a fact is encoded as an attachment, it is a separate object to the transaction and is referred to by hash. +Nodes download attachments from peers at the same time as they download transactions, unless of course the node has +already seen that attachment, in which case it won't fetch it again. Contracts have access to the contents of +attachments when they run. + +.. note:: Currently attachments do not support digital signing, but this is a planned feature. + +As you can see, both approaches share a few things: they both allow arbitrary binary data to be provided to transactions +(and thus contracts). The primary difference is whether the data is a freely reusable, standalone object or whether it's +integrated with a transaction. + +Here's a quick way to decide which approach makes more sense for your data source: + +* Is your data *continuously changing*, like a stock price, the current time, etc? If yes, use a command. +* Is your data *commercially valuable*, like a feed which you are not allowed to resell unless it's incorporated into + a business deal? If yes, use a command, so you can charge money for signing the same fact in each unique business + context. +* Is your data *very small*, like a single number? If yes, use a command. +* Is your data *large*, *static* and *commercially worthless*, for instance, a holiday calendar? If yes, use an + attachment. +* Is your data *intended for human consumption*, like a PDF of legal prose, or an Excel spreadsheet? If yes, use an + attachment. + +Asserting continuously varying data +----------------------------------- + +.. note:: A future version of the platform will include a complete tutorial on implementing this type of oracle. + +Let's look at the interest rates oracle that can be found in the ``NodeInterestRates`` file. This is an example of +an oracle that uses a command because the current interest rate fix is a constantly changing fact. + +The obvious way to implement such a service is like this: + +1. The creator of the transaction that depends on the interest rate sends it to the oracle. +2. The oracle inserts a command with the rate and signs the transaction. +3. The oracle sends it back. + +But this has a problem - it would mean that the oracle has to be the first entity to sign the transaction, which might impose +ordering constraints we don't want to deal with (being able to get all parties to sign in parallel is a very nice thing). +So the way we actually implement it is like this: + +1. The creator of the transaction that depends on the interest rate asks for the current rate. They can abort at this point + if they want to. +2. They insert a command with that rate and the time it was obtained into the transaction. +3. They then send it to the oracle for signing, along with everyone else in parallel. The oracle checks that the command + has correct data for the asserted time, and signs if so. + +This same technique can be adapted to other types of oracle. + +The oracle consists of a core class that implements the query/sign operations (for easy unit testing), and then a separate +class that binds it to the network layer. + +Here is an extract from the ``NodeService.Oracle`` class and supporting types: + +.. sourcecode:: kotlin + + /** A [FixOf] identifies the question side of a fix: what day, tenor and type of fix ("LIBOR", "EURIBOR" etc) */ + data class FixOf(val name: String, val forDay: LocalDate, val ofTenor: Duration) + + /** A [Fix] represents a named interest rate, on a given day, for a given duration. It can be embedded in a tx. */ + data class Fix(val of: FixOf, val value: BigDecimal) : CommandData + + class Oracle { + fun query(queries: List): List + + fun sign(wtx: WireTransaction): DigitalSignature.LegallyIdentifiable + } + +Because the fix contains a timestamp (the ``forDay`` field), there can be an arbitrary delay between a fix being +requested via ``query`` and the signature being requested via ``sign``. + +Pay-per-play oracles +-------------------- + +Because the signature covers the transaction, and transactions may end up being forwarded anywhere, the fact itself +is independently checkable. However, this approach can still be useful when the data itself costs money, because the act +of issuing the signature in the first place can be charged for (e.g. by requiring the submission of a fresh +``Cash.State`` that has been re-assigned to a key owned by the oracle service). Because the signature covers the +*transaction* and not only the *fact*, this allows for a kind of weak pseudo-DRM over data feeds. Whilst a smart +contract could in theory include a transaction parsing and signature checking library, writing a contract in this way +would be conclusive evidence of intent to disobey the rules of the service (*res ipsa loquitur*). In an environment +where parties are legally identifiable, usage of such a contract would by itself be sufficient to trigger some sort of +punishment. diff --git a/docs/build/html/_sources/persistence.txt b/docs/build/html/_sources/persistence.txt new file mode 100644 index 0000000000..ba7c15b94a --- /dev/null +++ b/docs/build/html/_sources/persistence.txt @@ -0,0 +1,89 @@ +Persistence +=========== + +Corda offers developers the option to expose all or some part of a contract state to an *Object Relational Mapping* (ORM) tool +to be persisted in a RDBMS. The purpose of this is to assist *vault* development by effectively indexing +persisted contract states held in the vault for the purpose of running queries over them and to allow relational joins +between Corda data and private data local to the organisation owning a node. + +The ORM mapping is specified using the `Java Persistence API `_ (JPA) +as annotations and is converted to database table rows by the node automatically every time a state is recorded in the +node's local vault as part of a transaction. + +.. note:: Presently the node includes an instance of the H2 database but any database that supports JDBC is a candidate and + the node will in the future support a range of database implementations via their JDBC drivers. Much of the node + internal state is also persisted there. You can access the internal H2 database via JDBC, please see the info + in ":doc:`node-administration`" for details. + +Schemas +------- + +Every ``ContractState`` can implement the ``QueryableState`` interface if it wishes to be inserted into the node's local +database and accessible using SQL. + +.. literalinclude:: ../../core/src/main/kotlin/net.corda.core/schemas/PersistentTypes.kt + :language: kotlin + :start-after: DOCSTART QueryableState + :end-before: DOCEND QueryableState + +The ``QueryableState`` interface requires the state to enumerate the different relational schemas it supports, for instance in +cases where the schema has evolved, with each one being represented by a ``MappedSchema`` object return by the +``supportedSchemas()`` method. Once a schema is selected it must generate that representation when requested via the +``generateMappedObject()`` method which is then passed to the ORM. + +Nodes have an internal ``SchemaService`` which decides what to persist and what not by selecting the ``MappedSchema`` +to use. + +.. literalinclude:: ../../node/src/main/kotlin/net.corda.node/services/api/SchemaService.kt + :language: kotlin + :start-after: DOCSTART SchemaService + :end-before: DOCEND SchemaService + +.. literalinclude:: ../../core/src/main/kotlin/net.corda.core/schemas/PersistentTypes.kt + :language: kotlin + :start-after: DOCSTART MappedSchema + :end-before: DOCEND MappedSchema + +The ``SchemaService`` can be configured by a node administrator to select the schemas used by each app. In this way the +relational view of ledger states can evolve in a controlled fashion in lock-step with internal systems or other +integration points and not necessarily with every upgrade to the contract code. +It can select from the ``MappedSchema`` offered by a ``QueryableState``, automatically upgrade to a +later version of a schema or even provide a ``MappedSchema`` not originally offered by the ``QueryableState``. + +It is expected that multiple different contract state implementations might provide mappings to some common schema. +For example an Interest Rate Swap contract and an Equity OTC Option contract might both provide a mapping to a common +Derivative schema. The schemas should typically not be part of the contract itself and should exist independently of it +to encourage re-use of a common set within a particular business area or Cordapp. + +``MappedSchema`` offer a family name that is disambiguated using Java package style name-spacing derived from the class name +of a *schema family* class that is constant across versions, allowing the ``SchemaService`` to select a preferred version +of a schema. + +The ``SchemaService`` is also responsible for the ``SchemaOptions`` that can be configured for a particular ``MappedSchema`` +which allow the configuration of a database schema or table name prefixes to avoid any clash with other ``MappedSchema``. + +.. note:: It is intended that there should be plugin support for the ``SchemaService`` to offer the version upgrading and + additional schemas as part of Cordapps, and that the active schemas be confgurable. However the present implementation + offers none of this and simply results in all versions of all schemas supported by a ``QueryableState`` being persisted. + This will change in due course. Similarly, it does not currently support configuring ``SchemaOptions`` but will do so in + the future. + +Object Relational Mapping +------------------------- + +The persisted representation of a ``QueryableState`` should be an instance of a ``PersistentState`` subclass, constructed +either by the state itself or a plugin to the ``SchemaService``. This allows the ORM layer to always associate a +``StateRef`` with a persisted representation of a ``ContractState`` and allows joining with the set of unconsumed states +in the vault. + +The ``PersistentState`` subclass should be marked up as a JPA 2.1 *Entity* with a defined table name and having +properties (in Kotlin, getters/setters in Java) annotated to map to the appropriate columns and SQL types. Additional +entities can be included to model these properties where they are more complex, for example collections, so the mapping +does not have to be *flat*. The ``MappedSchema`` must provide a list of all of the JPA entity classes for that schema in order +to initialise the ORM layer. + +Several examples of entities and mappings are provided in the codebase, including ``Cash.State`` and +``CommercialPaper.State``. For example, here's the first version of the cash schema. + +.. literalinclude:: ../../finance/src/main/kotlin/net.corda.schemas/CashSchemaV1.kt + :language: kotlin diff --git a/docs/build/html/_sources/protocol-state-machines.txt b/docs/build/html/_sources/protocol-state-machines.txt new file mode 100644 index 0000000000..e06b039fbf --- /dev/null +++ b/docs/build/html/_sources/protocol-state-machines.txt @@ -0,0 +1,694 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Protocol state machines +======================= + +This article explains our experimental approach to modelling financial protocols in code. It explains how the +platform's state machine framework is used, and takes you through the code for a simple 2-party asset trading protocol +which is included in the source. + +Introduction +------------ + +Shared distributed ledgers are interesting because they allow many different, mutually distrusting parties to +share a single source of truth about the ownership of assets. Digitally signed transactions are used to update that +shared ledger, and transactions may alter many states simultaneously and atomically. + +Blockchain systems such as Bitcoin support the idea of building up a finished, signed transaction by passing around +partially signed invalid transactions outside of the main network, and by doing this you can implement +*delivery versus payment* such that there is no chance of settlement failure, because the movement of cash and the +traded asset are performed atomically by the same transaction. To perform such a trade involves a multi-step protocol +in which messages are passed back and forth privately between parties, checked, signed and so on. + +Despite how useful these protocols are, platforms such as Bitcoin and Ethereum do not assist the developer with the rather +tricky task of actually building them. That is unfortunate. There are many awkward problems in their implementation +that a good platform would take care of for you, problems like: + +* Avoiding "callback hell" in which code that should ideally be sequential is turned into an unreadable mess due to the + desire to avoid using up a thread for every protocol instantiation. +* Surviving node shutdowns/restarts that may occur in the middle of the protocol without complicating things. This + implies that the state of the protocol must be persisted to disk. +* Error handling. +* Message routing. +* Serialisation. +* Catching type errors, in which the developer gets temporarily confused and expects to receive/send one type of message + when actually they need to receive/send another. +* Unit testing of the finished protocol. + +Actor frameworks can solve some of the above but they are often tightly bound to a particular messaging layer, and +we would like to keep a clean separation. Additionally, they are typically not type safe, and don't make persistence or +writing sequential code much easier. + +To put these problems in perspective, the *payment channel protocol* in the bitcoinj library, which allows bitcoins to +be temporarily moved off-chain and traded at high speed between two parties in private, consists of about 7000 lines of +Java and took over a month of full time work to develop. Most of that code is concerned with the details of persistence, +message passing, lifecycle management, error handling and callback management. Because the business logic is quite +spread out the code can be difficult to read and debug. + +As small contract-specific trading protocols are a common occurence in finance, we provide a framework for the +construction of them that automatically handles many of the concerns outlined above. + +Theory +------ + +A *continuation* is a suspended stack frame stored in a regular object that can be passed around, serialised, +unserialised and resumed from where it was suspended. This concept is sometimes referred to as "fibers". This may +sound abstract but don't worry, the examples below will make it clearer. The JVM does not natively support +continuations, so we implement them using a library called Quasar which works through behind-the-scenes +bytecode rewriting. You don't have to know how this works to benefit from it, however. + +We use continuations for the following reasons: + +* It allows us to write code that is free of callbacks, that looks like ordinary sequential code. +* A suspended continuation takes far less memory than a suspended thread. It can be as low as a few hundred bytes. + In contrast a suspended Java thread stack can easily be 1mb in size. +* It frees the developer from thinking (much) about persistence and serialisation. + +A *state machine* is a piece of code that moves through various *states*. These are not the same as states in the data +model (that represent facts about the world on the ledger), but rather indicate different stages in the progression +of a multi-stage protocol. Typically writing a state machine would require the use of a big switch statement and some +explicit variables to keep track of where you're up to. The use of continuations avoids this hassle. + +A two party trading protocol +---------------------------- + +We would like to implement the "hello world" of shared transaction building protocols: a seller wishes to sell some +*asset* (e.g. some commercial paper) in return for *cash*. The buyer wishes to purchase the asset using his cash. They +want the trade to be atomic so neither side is exposed to the risk of settlement failure. We assume that the buyer +and seller have found each other and arranged the details on some exchange, or over the counter. The details of how +the trade is arranged isn't covered in this article. + +Our protocol has two parties (B and S for buyer and seller) and will proceed as follows: + +1. S sends a ``StateAndRef`` pointing to the state they want to sell to B, along with info about the price they require + B to pay. +2. B sends to S a ``SignedTransaction`` that includes the state as input, B's cash as input, the state with the new + owner key as output, and any change cash as output. It contains a single signature from B but isn't valid because + it lacks a signature from S authorising movement of the asset. +3. S signs it and hands the now finalised ``SignedTransaction`` back to B. + +You can find the implementation of this protocol in the file ``finance/src/main/kotlin/net.corda.protocols/TwoPartyTradeProtocol.kt``. + +Assuming no malicious termination, they both end the protocol being in posession of a valid, signed transaction that +represents an atomic asset swap. + +Note that it's the *seller* who initiates contact with the buyer, not vice-versa as you might imagine. + +We start by defining a wrapper that namespaces the protocol code, two functions to start either the buy or sell side +of the protocol, and two classes that will contain the protocol definition. We also pick what data will be used by +each side. + +.. note:: The code samples in this tutorial are only available in Kotlin, but you can use any JVM language to + write them and the approach is the same. + +.. container:: codeset + + .. sourcecode:: kotlin + + object TwoPartyTradeProtocol { + + class UnacceptablePriceException(val givenPrice: Amount) : Exception("Unacceptable price: $givenPrice") + class AssetMismatchException(val expectedTypeName: String, val typeName: String) : Exception() { + override fun toString() = "The submitted asset didn't match the expected type: $expectedTypeName vs $typeName" + } + + // This object is serialised to the network and is the first protocol message the seller sends to the buyer. + data class SellerTradeInfo( + val assetForSale: StateAndRef, + val price: Amount, + val sellerOwnerKey: PublicKey + ) + + data class SignaturesFromSeller(val sellerSig: DigitalSignature.WithKey, + val notarySig: DigitalSignature.LegallyIdentifiable) + + open class Seller(val otherSide: Party, + val notaryNode: NodeInfo, + val assetToSell: StateAndRef, + val price: Amount, + val myKeyPair: KeyPair, + override val progressTracker: ProgressTracker = Seller.tracker()) : ProtocolLogic() { + @Suspendable + override fun call(): SignedTransaction { + TODO() + } + } + + open class Buyer(val otherSide: Party, + val notary: Party, + val acceptablePrice: Amount, + val typeToBuy: Class) : ProtocolLogic() { + @Suspendable + override fun call(): SignedTransaction { + TODO() + } + } + } + +This code defines several classes nested inside the main ``TwoPartyTradeProtocol`` singleton. Some of the classes are +simply protocol messages or exceptions. The other two represent the buyer and seller side of the protocol. + +Going through the data needed to become a seller, we have: + +- ``otherSide: Party`` - the party with which you are trading. +- ``notaryNode: NodeInfo`` - the entry in the network map for the chosen notary. See ":doc:`consensus`" for more + information on notaries. +- ``assetToSell: StateAndRef`` - a pointer to the ledger entry that represents the thing being sold. +- ``price: Amount`` - the agreed on price that the asset is being sold for (without an issuer constraint). +- ``myKeyPair: KeyPair`` - the key pair that controls the asset being sold. It will be used to sign the transaction. + +And for the buyer: + +- ``acceptablePrice: Amount`` - the price that was agreed upon out of band. If the seller specifies + a price less than or equal to this, then the trade will go ahead. +- ``typeToBuy: Class`` - the type of state that is being purchased. This is used to check that the + sell side of the protocol isn't trying to sell us the wrong thing, whether by accident or on purpose. + +Alright, so using this protocol shouldn't be too hard: in the simplest case we can just create a Buyer or Seller +with the details of the trade, depending on who we are. We then have to start the protocol in some way. Just +calling the ``call`` function ourselves won't work: instead we need to ask the framework to start the protocol for +us. More on that in a moment. + +Suspendable functions +--------------------- + +The ``call`` function of the buyer/seller classes is marked with the ``@Suspendable`` annotation. What does this mean? + +As mentioned above, our protocol framework will at points suspend the code and serialise it to disk. For this to work, +any methods on the call stack must have been pre-marked as ``@Suspendable`` so the bytecode rewriter knows to modify +the underlying code to support this new feature. A protocol is suspended when calling either ``receive``, ``send`` or +``sendAndReceive`` which we will learn more about below. For now, just be aware that when one of these methods is +invoked, all methods on the stack must have been marked. If you forget, then in the unit test environment you will +get a useful error message telling you which methods you didn't mark. The fix is simple enough: just add the annotation +and try again. + +.. note:: Java 9 is likely to remove this pre-marking requirement completely. + +Starting your protocol +---------------------- + +The ``StateMachineManager`` is the class responsible for taking care of all running protocols in a node. It knows +how to register handlers with the messaging system (see ":doc:`messaging`") and iterate the right state machine +when messages arrive. It provides the send/receive/sendAndReceive calls that let the code request network +interaction and it will save/restore serialised versions of the fiber at the right times. + +Protocols can be invoked in several ways. For instance, they can be triggered by scheduled events, +see ":doc:`event-scheduling`" to learn more about this. Or they can be triggered via the HTTP API. Or they can +be triggered directly via the Java-level node APIs from your app code. + +You request a protocol to be invoked by using the ``ServiceHub.invokeProtocolAsync`` method. This takes a +Java reflection ``Class`` object that describes the protocol class to use (in this case, either ``Buyer`` or ``Seller``). +It also takes a set of arguments to pass to the constructor. Because it's possible for protocol invocations to +be requested by untrusted code (e.g. a state that you have been sent), the types that can be passed into the +protocol are checked against a whitelist, which can be extended by apps themselves at load time. + +The process of starting a protocol returns a ``ListenableFuture`` that you can use to either block waiting for +the result, or register a callback that will be invoked when the result is ready. + +In a two party protocol only one side is to be manually started using ``ServiceHub.invokeProtocolAsync``. The other side +has to be registered by its node to respond to the initiating protocol via ``ServiceHubInternal.registerProtocolInitiator``. +In our example it doesn't matter which protocol is the initiator and which is the initiated. For example, if we are to +take the seller as the initiator then we would register the buyer as such: + +.. container:: codeset + + .. sourcecode:: kotlin + + val services: ServiceHubInternal = TODO() + + services.registerProtocolInitiator(Seller::class) { otherParty -> + val notary = services.networkMapCache.notaryNodes[0] + val acceptablePrice = TODO() + val typeToBuy = TODO() + Buyer(otherParty, notary, acceptablePrice, typeToBuy) + } + +This is telling the buyer node to fire up an instance of ``Buyer`` (the code in the lambda) when the initiating protocol +is a seller (``Seller::class``). + +Implementing the seller +----------------------- + +Let's implement the ``Seller.call`` method. This will be run when the protocol is invoked. + +.. container:: codeset + + .. sourcecode:: kotlin + + @Suspendable + override fun call(): SignedTransaction { + val partialTX: SignedTransaction = receiveAndCheckProposedTransaction() + val ourSignature: DigitalSignature.WithKey = computeOurSignature(partialTX) + val allPartySignedTx = partialTX + ourSignature + val notarySignature = getNotarySignature(allPartySignedTx) + val result: SignedTransaction = sendSignatures(allPartySignedTx, ourSignature, notarySignature) + return result + } + +Here we see the outline of the procedure. We receive a proposed trade transaction from the buyer and check that it's +valid. The buyer has already attached their signature before sending it. Then we calculate and attach our own signature so that the transaction is +now signed by both the buyer and the seller. We then send this request to a notary to assert with another signature that the +timestamp in the transaction (if any) is valid and there are no double spends, and send back both +our signature and the notaries signature. Note we should not send to the notary until all other required signatures have been appended +as the notary may validate the signatures as well as verifying for itself the transactional integrity. +Finally, we hand back to the code that invoked the protocol the finished transaction. + +Let's fill out the ``receiveAndCheckProposedTransaction()`` method. + +.. container:: codeset + + .. sourcecode:: kotlin + + @Suspendable + private fun receiveAndCheckProposedTransaction(): SignedTransaction { + // Make the first message we'll send to kick off the protocol. + val hello = SellerTradeInfo(assetToSell, price, myKeyPair.public) + + val maybeSTX = sendAndReceive(otherSide, hello) + + maybeSTX.unwrap { + // Check that the tx proposed by the buyer is valid. + val missingSigs: Set = it.verifySignatures(throwIfSignaturesAreMissing = false) + val expected = setOf(myKeyPair.public, notaryNode.identity.owningKey) + if (missingSigs != expected) + throw SignatureException("The set of missing signatures is not as expected: ${missingSigs.toStringsShort()} vs ${expected.toStringsShort()}") + + val wtx: WireTransaction = it.tx + logger.trace { "Received partially signed transaction: ${it.id}" } + + // Download and check all the things that this transaction depends on and verify it is contract-valid, + // even though it is missing signatures. + subProtocol(ResolveTransactionsProtocol(wtx, otherSide)) + + if (wtx.outputs.map { it.data }.sumCashBy(myKeyPair.public).withoutIssuer() != price) + throw IllegalArgumentException("Transaction is not sending us the right amount of cash") + + return it + } + } + +Let's break this down. We fill out the initial protocol message with the trade info, and then call ``sendAndReceive``. +This function takes a few arguments: + +- The party on the other side. +- The thing to send. It'll be serialised and sent automatically. +- Finally a type argument, which is the kind of object we're expecting to receive from the other side. If we get + back something else an exception is thrown. + +Once ``sendAndReceive`` is called, the call method will be suspended into a continuation and saved to persistent +storage. If the node crashes or is restarted, the protocol will effectively continue as if nothing had happened. Your +code may remain blocked inside such a call for seconds, minutes, hours or even days in the case of a protocol that +needs human interaction! + +.. note:: There are a couple of rules you need to bear in mind when writing a class that will be used as a continuation. + The first is that anything on the stack when the function is suspended will be stored into the heap and kept alive by + the garbage collector. So try to avoid keeping enormous data structures alive unless you really have to. + + The second is that as well as being kept on the heap, objects reachable from the stack will be serialised. The state + of the function call may be resurrected much later! Kryo doesn't require objects be marked as serialisable, but even so, + doing things like creating threads from inside these calls would be a bad idea. They should only contain business + logic and only do I/O via the methods exposed by the protocol framework. + + It's OK to keep references around to many large internal node services though: these will be serialised using a + special token that's recognised by the platform, and wired up to the right instance when the continuation is + loaded off disk again. + +The buyer is supposed to send us a transaction with all the right inputs/outputs/commands in response to the opening +message, with their cash put into the transaction and their signature on it authorising the movement of the cash. + +You get back a simple wrapper class, ``UntrustworthyData``, which is just a marker class that reminds +us that the data came from a potentially malicious external source and may have been tampered with or be unexpected in +other ways. It doesn't add any functionality, but acts as a reminder to "scrub" the data before use. + +Our "scrubbing" has three parts: + +1. Check that the expected signatures are present and correct. At this point we expect our own signature to be missing, + because of course we didn't sign it yet, and also the signature of the notary because that must always come last. +2. We resolve the transaction, which we will cover below. +3. We verify that the transaction is paying us the demanded price. + +Subprotocols +------------ + +Protocols can be composed via nesting. Invoking a sub-protocol looks similar to an ordinary function call: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Suspendable + private fun getNotarySignature(stx: SignedTransaction): DigitalSignature.LegallyIdentifiable { + progressTracker.currentStep = NOTARY + return subProtocol(NotaryProtocol.Client(stx)) + } + +In this code snippet we are using the ``NotaryProtocol.Client`` to request notarisation of the transaction. +We simply create the protocol object via its constructor, and then pass it to the ``subProtocol`` method which +returns the result of the protocol's execution directly. Behind the scenes all this is doing is wiring up progress +tracking (discussed more below) and then running the objects ``call`` method. Because this little helper method can +be on the stack when network IO takes place, we mark it as ``@Suspendable``. + +Going back to the previous code snippet, we use a subprotocol called ``ResolveTransactionsProtocol``. This is +responsible for downloading and checking all the dependencies of a transaction, which in Corda are always retrievable +from the party that sent you a transaction that uses them. This protocol returns a list of ``LedgerTransaction`` +objects, but we don't need them here so we just ignore the return value. + +.. note:: Transaction dependency resolution assumes that the peer you got the transaction from has all of the + dependencies itself. It must do, otherwise it could not have convinced itself that the dependencies were themselves + valid. It's important to realise that requesting only the transactions we require is a privacy leak, because if + we don't download a transaction from the peer, they know we must have already seen it before. Fixing this privacy + leak will come later. + +After the dependencies, we check the proposed trading transaction for validity by running the contracts for that as +well (but having handled the fact that some signatures are missing ourselves). + +Here's the rest of the code: + +.. container:: codeset + + .. sourcecode:: kotlin + + open fun computeOurSignature(partialTX: SignedTransaction) = myKeyPair.signWithECDSA(partialTX.txBits) + + @Suspendable + private fun sendSignatures(allPartySignedTX: SignedTransaction, ourSignature: DigitalSignature.WithKey, + notarySignature: DigitalSignature.LegallyIdentifiable): SignedTransaction { + val fullySigned = allPartySignedTX + notarySignature + logger.trace { "Built finished transaction, sending back to secondary!" } + send(otherSide, SignaturesFromSeller(ourSignature, notarySignature)) + return fullySigned + } + +It's all pretty straightforward from now on. Here ``txBits`` is the raw byte array representing the serialised +transaction, and we just use our private key to calculate a signature over it. As a reminder, in Corda signatures do +not cover other signatures: just the core of the transaction data. + +In ``sendSignatures``, we take the two signatures we obtained and add them to the partial transaction we were sent. +There is an overload for the + operator so signatures can be added to a SignedTransaction easily. Finally, we wrap the +two signatures in a simple wrapper message class and send it back. The send won't block waiting for an acknowledgement, +but the underlying message queue software will retry delivery if the other side has gone away temporarily. + +You can also see that every protocol instance has a logger (using the SLF4J API) which you can use to log progress +messages. + +.. warning:: This sample code is **not secure**. Other than not checking for all possible invalid constructions, if the + seller stops before sending the finalised transaction to the buyer, the seller is left with a valid transaction + but the buyer isn't, so they can't spend the asset they just purchased! This sort of thing will be fixed in a + future version of the code. + +Implementing the buyer +---------------------- + +OK, let's do the same for the buyer side: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Suspendable + override fun call(): SignedTransaction { + val tradeRequest = receiveAndValidateTradeRequest() + val (ptx, cashSigningPubKeys) = assembleSharedTX(tradeRequest) + val stx = signWithOurKeys(cashSigningPubKeys, ptx) + + val signatures = swapSignaturesWithSeller(stx) + + logger.trace { "Got signatures from seller, verifying ... " } + + val fullySigned = stx + signatures.sellerSig + signatures.notarySig + fullySigned.verifySignatures() + + logger.trace { "Signatures received are valid. Trade complete! :-)" } + return fullySigned + } + + @Suspendable + private fun receiveAndValidateTradeRequest(): SellerTradeInfo { + // Wait for a trade request to come in from the other side + val maybeTradeRequest = receive(otherParty) + maybeTradeRequest.unwrap { + // What is the seller trying to sell us? + val asset = it.assetForSale.state.data + val assetTypeName = asset.javaClass.name + logger.trace { "Got trade request for a $assetTypeName: ${it.assetForSale}" } + + if (it.price > acceptablePrice) + throw UnacceptablePriceException(it.price) + if (!typeToBuy.isInstance(asset)) + throw AssetMismatchException(typeToBuy.name, assetTypeName) + + // Check the transaction that contains the state which is being resolved. + // We only have a hash here, so if we don't know it already, we have to ask for it. + subProtocol(ResolveTransactionsProtocol(setOf(it.assetForSale.ref.txhash), otherSide)) + + return it + } + } + + @Suspendable + private fun swapSignaturesWithSeller(stx: SignedTransaction): SignaturesFromSeller { + progressTracker.currentStep = SWAPPING_SIGNATURES + logger.trace { "Sending partially signed transaction to seller" } + + // TODO: Protect against the seller terminating here and leaving us in the lurch without the final tx. + + return sendAndReceive(otherSide, stx).unwrap { it } + } + + private fun signWithOurKeys(cashSigningPubKeys: List, ptx: TransactionBuilder): SignedTransaction { + // Now sign the transaction with whatever keys we need to move the cash. + for (k in cashSigningPubKeys) { + val priv = serviceHub.keyManagementService.toPrivate(k) + ptx.signWith(KeyPair(k, priv)) + } + + return ptx.toSignedTransaction(checkSufficientSignatures = false) + } + + private fun assembleSharedTX(tradeRequest: SellerTradeInfo): Pair> { + val ptx = TransactionType.General.Builder(notary) + // Add input and output states for the movement of cash, by using the Cash contract to generate the states. + val wallet = serviceHub.walletService.currentWallet + val cashStates = wallet.statesOfType() + val cashSigningPubKeys = Cash().generateSpend(ptx, tradeRequest.price, tradeRequest.sellerOwnerKey, cashStates) + // Add inputs/outputs/a command for the movement of the asset. + ptx.addInputState(tradeRequest.assetForSale) + // Just pick some new public key for now. This won't be linked with our identity in any way, which is what + // we want for privacy reasons: the key is here ONLY to manage and control ownership, it is not intended to + // reveal who the owner actually is. The key management service is expected to derive a unique key from some + // initial seed in order to provide privacy protection. + val freshKey = serviceHub.keyManagementService.freshKey() + val (command, state) = tradeRequest.assetForSale.state.data.withNewOwner(freshKey.public) + ptx.addOutputState(state, tradeRequest.assetForSale.state.notary) + ptx.addCommand(command, tradeRequest.assetForSale.state.data.owner) + + // And add a request for timestamping: it may be that none of the contracts need this! But it can't hurt + // to have one. + val currentTime = serviceHub.clock.instant() + ptx.setTime(currentTime, 30.seconds) + return Pair(ptx, cashSigningPubKeys) + } + +This code is longer but no more complicated. Here are some things to pay attention to: + +1. We do some sanity checking on the received message to ensure we're being offered what we expected to be offered. +2. We create a cash spend in the normal way, by using ``Cash().generateSpend``. See the contracts tutorial if this + part isn't clear. +3. We access the *service hub* when we need it to access things that are transient and may change or be recreated + whilst a protocol is suspended, things like the wallet or the network map. +4. Finally, we send the unfinished, invalid transaction to the seller so they can sign it. They are expected to send + back to us a ``SignaturesFromSeller``, which once we verify it, should be the final outcome of the trade. + +As you can see, the protocol logic is straightforward and does not contain any callbacks or network glue code, despite +the fact that it takes minimal resources and can survive node restarts. + +.. warning:: In the current version of the platform, exceptions thrown during protocol execution are not propagated + back to the sender. A thorough error handling and exceptions framework will be in a future version of the platform. + +Progress tracking +----------------- + +Not shown in the code snippets above is the usage of the ``ProgressTracker`` API. Progress tracking exports information +from a protocol about where it's got up to in such a way that observers can render it in a useful manner to humans who +may need to be informed. It may be rendered via an API, in a GUI, onto a terminal window, etc. + +A ``ProgressTracker`` is constructed with a series of ``Step`` objects, where each step is an object representing a +stage in a piece of work. It is therefore typical to use singletons that subclass ``Step``, which may be defined easily +in one line when using Kotlin. Typical steps might be "Waiting for response from peer", "Waiting for signature to be +approved", "Downloading and verifying data" etc. + +Each step exposes a label. By default labels are fixed, but by subclassing ``RelabelableStep`` +you can make a step that can update its label on the fly. That's useful for steps that want to expose non-structured +progress information like the current file being downloaded. By defining your own step types, you can export progress +in a way that's both human readable and machine readable. + +Progress trackers are hierarchical. Each step can be the parent for another tracker. By altering the +``ProgressTracker.childrenFor[step] = tracker`` map, a tree of steps can be created. It's allowed to alter the hierarchy +at runtime, on the fly, and the progress renderers will adapt to that properly. This can be helpful when you don't +fully know ahead of time what steps will be required. If you _do_ know what is required, configuring as much of the +hierarchy ahead of time is a good idea, as that will help the users see what is coming up. + +Every tracker has not only the steps given to it at construction time, but also the singleton +``ProgressTracker.UNSTARTED`` step and the ``ProgressTracker.DONE`` step. Once a tracker has become ``DONE`` its +position may not be modified again (because e.g. the UI may have been removed/cleaned up), but until that point, the +position can be set to any arbitrary set both forwards and backwards. Steps may be skipped, repeated, etc. Note that +rolling the current step backwards will delete any progress trackers that are children of the steps being reversed, on +the assumption that those subtasks will have to be repeated. + +Trackers provide an `Rx observable `_ which streams changes to the hierarchy. The top level +observable exposes all the events generated by its children as well. The changes are represented by objects indicating +whether the change is one of position (i.e. progress), structure (i.e. new subtasks being added/removed) or some other +aspect of rendering (i.e. a step has changed in some way and is requesting a re-render). + +The protocol framework is somewhat integrated with this API. Each ``ProtocolLogic`` may optionally provide a tracker by +overriding the ``protocolTracker`` property (``getProtocolTracker`` method in Java). If the +``ProtocolLogic.subProtocol`` method is used, then the tracker of the sub-protocol will be made a child of the current +step in the parent protocol automatically, if the parent is using tracking in the first place. The framework will also +automatically set the current step to ``DONE`` for you, when the protocol is finished. + +Because a protocol may sometimes wish to configure the children in its progress hierarchy _before_ the sub-protocol +is constructed, for sub-protocols that always follow the same outline regardless of their parameters it's conventional +to define a companion object/static method (for Kotlin/Java respectively) that constructs a tracker, and then allow +the sub-protocol to have the tracker it will use be passed in as a parameter. This allows all trackers to be built +and linked ahead of time. + +In future, the progress tracking framework will become a vital part of how exceptions, errors, and other faults are +surfaced to human operators for investigation and resolution. + +Unit testing +------------ + +A protocol can be a fairly complex thing that interacts with many services and other parties over the network. That +means unit testing one requires some infrastructure to provide lightweight mock implementations. The MockNetwork +provides this testing infrastructure layer; you can find this class in the node module + +A good example to examine for learning how to unit test protocols is the ``ResolveTransactionsProtocol`` tests. This +protocol takes care of downloading and verifying transaction graphs, with all the needed dependencies. We start +with this basic skeleton: + +.. container:: codeset + + .. sourcecode:: kotlin + + class ResolveTransactionsProtocolTest { + lateinit var net: MockNetwork + lateinit var a: MockNetwork.MockNode + lateinit var b: MockNetwork.MockNode + lateinit var notary: Party + + @Before + fun setup() { + net = MockNetwork() + val nodes = net.createSomeNodes() + a = nodes.partyNodes[0] + b = nodes.partyNodes[1] + notary = nodes.notaryNode.info.identity + net.runNetwork() + } + + @After + fun tearDown() { + net.stopNodes() + } + } + +We create a mock network in our ``@Before`` setup method and create a couple of nodes. We also record the identity +of the notary in our test network, which will come in handy later. We also tidy up when we're done. + +Next, we write a test case: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun resolveFromTwoHashes() { + val (stx1, stx2) = makeTransactions() + val p = ResolveTransactionsProtocol(setOf(stx2.id), a.info.identity) + val future = b.services.startProtocol("resolve", p) + net.runNetwork() + val results = future.get() + assertEquals(listOf(stx1.id, stx2.id), results.map { it.id }) + assertEquals(stx1, b.storage.validatedTransactions.getTransaction(stx1.id)) + assertEquals(stx2, b.storage.validatedTransactions.getTransaction(stx2.id)) + } + +We'll take a look at the ``makeTransactions`` function in a moment. For now, it's enough to know that it returns two +``SignedTransaction`` objects, the second of which spends the first. Both transactions are known by node A +but not node B. + +The test logic is simple enough: we create the protocol, giving it node A's identity as the target to talk to. +Then we start it on node B and use the ``net.runNetwork()`` method to bounce messages around until things have +settled (i.e. there are no more messages waiting to be delivered). All this is done using an in memory message +routing implementation that is fast to initialise and use. Finally, we obtain the result of the protocol and do +some tests on it. We also check the contents of node B's database to see that the protocol had the intended effect +on the node's persistent state. + +Here's what ``makeTransactions`` looks like: + +.. container:: codeset + + .. sourcecode:: kotlin + + private fun makeTransactions(): Pair { + // Make a chain of custody of dummy states and insert into node A. + val dummy1: SignedTransaction = DummyContract.generateInitial(MEGA_CORP.ref(1), 0, notary).let { + it.signWith(MEGA_CORP_KEY) + it.signWith(DUMMY_NOTARY_KEY) + it.toSignedTransaction(false) + } + val dummy2: SignedTransaction = DummyContract.move(dummy1.tx.outRef(0), MINI_CORP_PUBKEY).let { + it.signWith(MEGA_CORP_KEY) + it.signWith(DUMMY_NOTARY_KEY) + it.toSignedTransaction() + } + a.services.recordTransactions(dummy1, dummy2) + return Pair(dummy1, dummy2) + } + +We're using the ``DummyContract``, a simple test smart contract which stores a single number in its states, along +with ownership and issuer information. You can issue such states, exit them and re-assign ownership (move them). +It doesn't do anything else. This code simply creates a transaction that issues a dummy state (the issuer is +``MEGA_CORP``, a pre-defined unit test identity), signs it with the test notary and MegaCorp keys and then +converts the builder to the final ``SignedTransaction``. It then does so again, but this time instead of issuing +it re-assigns ownership instead. The chain of two transactions is finally committed to node A by sending them +directly to the ``a.services.recordTransaction`` method (note that this method doesn't check the transactions are +valid). + +And that's it: you can explore the documentation for the `MockNode API `_ here. + +Versioning +---------- + +Fibers involve persisting object-serialised stack frames to disk. Although we may do some R&D into in-place upgrades +in future, for now the upgrade process for protocols is simple: you duplicate the code and rename it so it has a +new set of class names. Old versions of the protocol can then drain out of the system whilst new versions are +initiated. When enough time has passed that no old versions are still waiting for anything to happen, the previous +copy of the code can be deleted. + +Whilst kind of ugly, this is a very simple approach that should suffice for now. + +.. warning:: Protocols are not meant to live for months or years, and by implication they are not meant to implement entire deal + lifecycles. For instance, implementing the entire life cycle of an interest rate swap as a single protocol - whilst + technically possible - would not be a good idea. The platform provides a job scheduler tool that can invoke + protocols for this reason (see ":doc:`event-scheduling`") + +Future features +--------------- + +The protocol framework is a key part of the platform and will be extended in major ways in future. Here are some of +the features we have planned: + +* Identity based addressing +* Exposing progress trackers to local (inside the firewall) clients using message queues and/or WebSockets +* Exception propagation and management, with a "protocol hospital" tool to manually provide solutions to unavoidable + problems (e.g. the other side doesn't know the trade) +* Being able to interact with internal apps and tools via HTTP and similar +* Being able to interact with people, either via some sort of external ticketing system, or email, or a custom UI. + For example to implement human transaction authorisations. +* A standard library of protocols that can be easily sub-classed by local developers in order to integrate internal + reporting logic, or anything else that might be required as part of a communications lifecycle. diff --git a/docs/build/html/_sources/release-notes.txt b/docs/build/html/_sources/release-notes.txt new file mode 100644 index 0000000000..77a8fd17a0 --- /dev/null +++ b/docs/build/html/_sources/release-notes.txt @@ -0,0 +1,308 @@ +Release notes +============= + +Here are brief summaries of what's changed between each snapshot release. + +Milestone 5 +----------- + +* A simple RPC access control mechanism. Users, passwords and permissions can be defined in a configuration file. + This mechanism will be extended in future to support standard authentication systems like LDAP. + +* New features in the explorer app and RPC API for working with cash: + + * Cash can now be sent, issued and exited via RPC. + * Notes can now be associated with transactions. + * Hashes are visually represented using identicons. + * Lots of functional work on the explorer UI. You can try it out by running ``gradle tools:explorer:runDemoNodes`` to run + a local network of nodes that swap cash with each other, and then run ``gradle tools:explorer:run`` to start + the app. + +* A new demo showing shared valuation of derivatives portfolios using the ISDA SIMM has been added. Note that this app + relies on a proprietary implementation of the ISDA SIMM business logic from OpenGamma. A stub library is provided + to ensure it compiles but if you want to use the app for real please contact us. + +* Developer experience (we plan to do lots more here in milestone 6): + + * Demos and samples have been split out of the main repository, and the initial developer experience continues to be + refined. All necessary JARs can now be installed to Maven Local by simply running ``gradle install``. + * It's now easier to define a set of nodes to run locally using the new "CordFormation" gradle plugin, which + defines a simple DSL for creating networks of nodes. + * The template CorDapp has been upgraded with more documentation and showing more features. + +* Privacy: transactions are now structured as Merkle trees, and can have sections "torn off" - presented for + verification and signing without revealing the rest of the transaction. + +* Lots of bug fixes, tweaks and polish starting the run up to the open source release. + +API changes: + +* Plugin service classes now take a ``PluginServiceHub`` rather than a ``ServiceHubInternal``. +* ``UniqueIdentifier`` equality has changed to only take into account the underlying UUID. +* The contracts module has been renamed to finance, to better reflect what it is for. + +Milestone 4 +----------- + +New features in this release: + +* Persistence: + + * States can now be written into a relational database and queried using JDBC. The schemas are defined by the + smart contracts and schema versioning is supported. It is reasonable to write an app that stores data in a mix + of global ledger transactions and local database tables which are joined on demand, using join key slots that + are present in many state definitions. Read more about :doc:`persistence`. + * The embedded H2 SQL database is now exposed by default to any tool that can speak JDBC. The database URL is + printed during node startup and can be used to explore the database, which contains both node internal data + and tables generated from ledger states. + * Protocol checkpoints are now stored in the database as well. Message processing is now atomic with protocol + checkpointing and run under the same RDBMS transaction. + * MQ message deduplication is now handled at the app layer and performed under the RDMS transaction, so + ensuring messages are only replayed if the RDMS transaction rolled back. + * "The wallet" has been renamed to "the vault". + +* Client RPC: + + * New RPCs added to subscribe to snapshots and update streams state of the vault, currently executing protocols + and other important node information. + * New tutorial added that shows how to use the RPC API to draw live transaction graphs on screen. + +* Protocol framework: + + * Large simplifications to the API. Session management is now handled automatically. Messages are now routed + based on identities rather than node IP addresses. + +* Decentralised consensus: + + * A standalone one-node notary backed by a JDBC store has been added. + * A prototype RAFT based notary composed of multiple nodes is available on a branch. + +* Data model: + + * Compound keys have been added as preparation for merging a distributed RAFT based notary. Compound keys + are trees of public keys in which interior nodes can have validity thresholds attached, thus allowing + boolean formulas of keys to be created. This is similar to Bitcoin's multi-sig support and the data model + is the same as the InterLedger Crypto-Conditions spec, which should aid interop in future. Read more about + key trees in the ":doc:`transaction-data-types`" article. + * A new tutorial has been added showing how to use transaction attachments in more detail. + +* Testnet + + * Permissioning infrastructure phase one is built out. The node now has a notion of developer mode vs normal + mode. In developer mode it works like M3 and the SSL certificates used by nodes running on your local + machine all self-sign using a developer key included in the source tree. When developer mode is not active, + the node won't start until it has a signed certificate. Such a certificate can be obtained by simply running + an included command line utility which generates a CSR and submits it to a permissioning service, then waits + for the signed certificate to be returned. Note that currently there is no public Corda testnet, so we are + not currently running a permissioning service. + +* Standalone app development: + + * The Corda libraries that app developers need to link against can now be installed into your local Maven + repository, where they can then be used like any other JAR. See :doc:`creating-a-cordapp`. + +* User interfaces: + + * Infrastructure work on the node explorer is now complete: it is fully switched to using the MQ based RPC system. + * A library of additional reactive collections has been added. This API builds on top of Rx and the observable + collections API in Java 8 to give "live" data structures in which the state of the node and ledger can be + viewed as an ordinary Java ``List``, ``Map`` and ``Set``, but which also emit callbacks when these views + change, and which can have additional views derived in a functional manner (filtered, mapped, sorted, etc). + Finally, these views can then be bound directly into JavaFX UIs. This makes for a concise and functional + way of building application UIs that render data from the node, and the API is available for third party + app developers to use as well. We believe this will be highly productive and enjoyable for developers who + have the option of building JavaFX apps (vs web apps). + * The visual network simulator tool that was demoed back in April as part of the first Corda live demo has + been merged into the main repository. + +* Documentation + + * New secure coding guidelines. Corda tries to eliminate as many security mistakes as practical via the type + system and other mechanically checkable processes, but there are still things that one must be aware of. + * New attachments tutorial. + * New Client RPC tutorial. + * More tutorials on how to build a standalone CorDapp. + +* Testing + + * More integration testing support + * New micro-DSLs for expressing expected sequences of operations with more or less relaxed ordering constraints. + * QuickCheck generators to create streams of randomised transactions and other basic types. QuickCheck is a way + of writing unit tests that perform randomised fuzz testing of code, originally developed by the Haskell + community and now also available in Java. + +API changes: + +* The transaction types (Signed, Wire, LedgerTransaction) have moved to ``net.corda.core.transactions``. You can + update your code by just deleting the broken import lines and letting your IDE re-import them from the right + location. +* ``AbstractStateReplacementProtocol.verifyProposal`` has changed its prototype in a minor way. +* The ``UntrustworthyData.validate`` method has been renamed to ``unwrap`` - the old name is now deprecated. +* The wallet, wallet service, etc. are now vault, vault service, etc. These better reflect the intent that they + are a generic secure data store, rather than something which holds cash. +* The protocol send/receive APIs have changed to no longer require a session id. Please check the current version + of the protocol framework tutorial for more details. + +Milestone 3 +----------- + +* More work on preparing for the testnet: + + * Corda is now a standalone app server that loads "CorDapps" into itself as plugins. Whilst the existing IRS + and trader demos still exist for now, these will soon be removed and there will only be a single Corda node + program. Note that the node is a single, standalone jar file that is easier to execute than the demos. + * Project Vega (shared SIMM modelling for derivative portfolios) has already been converted to be a CorDapp. + * Significant work done on making the node persist its wallet data to a SQL backend, with more on the way. + * Upgrades and refactorings of the core transaction types in preparation for the incoming sandboxing work. + +* The Clauses API that seeks to make writing smart contracts easier has gone through another design iteration, + with the result that clauses are now cleaner and more composable. +* Improvements to the protocol API for finalising transactions (notarising, transmitting and storing). +* Lots of work done on an MQ based client API. +* Improvements to the developer site: + + * The developer site has been re-read from start to finish and refreshed for M3 so there should be no obsolete + texts or references anywhere. + * The Corda non-technical white paper is now a part of the developer site and git repository. The LaTeX source is + also provided so if you spot any issues with it, you can send us patches. + * There is a new section on how to write CorDapps. + +* Further R&D work by Sofus Mortensen in the experimental module on a new 'universal' contract language. +* SSL for the REST API and webapp server can now be configured. + + +Milestone 2 +----------- + +* Big improvements to the interest rate swap app: + + * A new web app demonstrating the IRS contract has been added. This can be used as an example for how to interact with + the Corda API from the web. + * Simplifications to the way the demo is used from the command line. + * :doc:`Detailed documentation on how the contract works and can be used ` has been written. + * Better integration testing of the app. + +* Smart contracts have been redesigned around reusable components, referred to as "clauses". The cash, commercial paper + and obligation contracts now share a common issue clause. +* New code in the experimental module (note that this module is a place for work-in-progress code which has not yet gone + through code review and which may, in general, not even function correctly): + + * Thanks to the prolific Sofus Mortensen @ Nordea Bank, an experimental generic contract DSL that is based on the famous + 2001 "Composing contracts" paper has been added. We thank Sofus for this great and promising research, which is so + relevant in the wake of TheDAO hack. + * The contract code from the recent trade finance demos is now in experimental. This code comes thanks to a + collaboration of the members; all credit to: + + * Mustafa Ozturk @ Natixis + * David Nee @ US Bank + * Johannes Albertsen @ Dankse Bank + * Rui Hu @ Nordea + * Daniele Barreca @ Unicredit + * Sukrit Handa @ Scotiabank + * Giuseppe Cardone @ Banco Intesa + * Robert Santiago @ BBVA + +* The usability of the command line demo programs has been improved. +* All example code and existing contracts have been ported to use the new Java/Kotlin unit testing domain-specific + languages (DSLs) which make it easy to construct chains of transactions and verify them together. This cleans up + and unifies the previous ad-hoc set of similar DSLs. A tutorial on how to use it has been added to the documentation. + We believe this largely completes our testing story for now around smart contracts. Feedback from bank developers + during the Trade Finance project has indicated that the next thing to tackle is docs and usability improvements in + the protocols API. +* Significant work done towards defining the "CorDapp" concept in code, with dynamic loading of API services and more to + come. +* Inter-node communication now uses SSL/TLS and AMQP/1.0, albeit without all nodes self-signing at the moment. A real + PKI for the p2p network will come later. +* Logging is now saved to files with log rotation provided by Log4J. + +API changes: + +* Some utility methods and extension functions that are specific to certain contract types have moved packages: just + delete the import lines that no longer work and let IntelliJ replace them with the correct package paths. +* The ``arg`` method in the test DSL is now called ``command`` to be consistent with the rest of the data model. +* The messaging APIs have changed somewhat to now use a new ``TopicSession`` object. These APIs will continue to change + in the upcoming releases. +* Clauses now have default values provided for ``ifMatched``, ``ifNotMatched`` and ``requiredCommands``. + +New documentation: + +* :doc:`contract-catalogue` +* :doc:`contract-irs` +* :doc:`tutorial-test-dsl` + +Milestone 1 +----------- + +Highlights of this release: + +* Event scheduling. States in the ledger can now request protocols to be invoked at particular times, for states + considered relevant by the wallet. +* Upgrades to the notary/consensus service support: + + * There is now a way to change the notary controlling a state. + * You can pick between validating and non-validating notaries, these let you select your privacy/robustness tradeoff. + +* A new obligation contract that supports bilateral and multilateral netting of obligations, default tracking and + more. +* Improvements to the financial type system, with core classes and contracts made more generic. +* Switch to a better digital signature algorithm: ed25519 instead of the previous JDK default of secp256r1. +* A new integration test suite. +* A new Java unit testing DSL for contracts, similar in spirit to the one already developed for Kotlin users (which + depended on Kotlin specific features). +* An experimental module, where developers who want to work with the latest Corda code can check in contracts/cordapp + code before it's been fully reviewed. Code in this module has compiler warnings suppressed but we will still make + sure it compiles across refactorings. +* Persistence improvements: transaction data is now stored to disk and automatic protocol resume is now implemented. +* Many smaller bug fixes, cleanups and improvements. + +We have new documentation on: + +* :doc:`event-scheduling` +* :doc:`transaction-data-types` +* :doc:`consensus` + +Summary of API changes (not exhaustive): + +* Notary/consensus service: + + * ``NotaryService`` is now extensible. + * Every ``ContractState`` now has to specify a *participants* field, which is a list of parties that are able to + consume this state in a valid transaction. This is used for e.g. making sure all relevant parties obtain the updated + state when changing a notary. + * Introduced ``TransactionState``, which wraps ``ContractState``, and is used when defining a transaction output. + The notary field is moved from ``ContractState`` into ``TransactionState``. + * Every transaction now has a *type* field, which specifies custom build & validation rules for that transaction type. + Currently two types are supported: General (runs the default build and validation logic) and NotaryChange ( + contract code is not run during validation, checks that the notary field is the only difference between the + inputs and outputs). + ``TransactionBuilder()`` is now abstract, you should use ``TransactionType.General.Builder()`` for building transactions. + +* The cash contract has moved from ``net.corda.contracts`` to ``net.corda.contracts.cash`` +* ``Amount`` class is now generic, to support non-currency types such as physical assets. Where you previously had just + ``Amount``, you should now use ``Amount``. +* Refactored the Cash contract to have a new FungibleAsset superclass, to model all countable assets that can be merged + and split (currency, barrels of oil, etc.) +* Messaging: + + * ``addMessageHandler`` now has a different signature as part of error handling changes. + * If you want to return nothing to a protocol, use ``Ack`` instead of ``Unit`` from now on. + +* In the IRS contract, dateOffset is now an integer instead of an enum. +* In contracts, you now use ``tx.getInputs`` and ``tx.getOutputs`` instead of ``getInStates`` and ``getOutStates``. This is + just a renaming. +* A new ``NonEmptySet`` type has been added for cases where you wish to express that you have a collection of unique + objects which cannot be empty. +* Please use the global ``newSecureRandom()`` function rather than instantiating your own SecureRandom's from now on, as + the custom function forces the use of non-blocking random drivers on Linux. + +Milestone 0 +----------- + +This is the first release, which includes: + +* Some initial smart contracts: cash, commercial paper, interest rate swaps +* An interest rate oracle +* The first version of the protocol/orchestration framework +* Some initial support for pluggable consensus mechanisms +* Tutorials and documentation explaining how it works +* Much more ... diff --git a/docs/build/html/_sources/release-process.txt b/docs/build/html/_sources/release-process.txt new file mode 100644 index 0000000000..2fcc8f1e58 --- /dev/null +++ b/docs/build/html/_sources/release-process.txt @@ -0,0 +1,44 @@ +Release process +=============== + +Corda is under heavy development. The current release process is therefore geared towards rapid iteration. + +Each Corda development release is called a *milestone* and has its own branch in the git repository. Milestones are +temporarily stabilised snapshots of the Corda code which are suitable for developers to experiment with. They may +receive backported bugfixes but once announced a milestone will not have any API or backwards compatibility breaks. + +Between milestones backwards compatibility is expected to break. Every new milestone comes with a short announcement +detailing: + +* What major improvements have been made. +* How to forward port your code to the new milestone. +* What new documentation has become available. +* Important known issues. + +Eventually, Corda will stabilise and release version 1. At that point backwards compatibility will be guaranteed +forever and the software will be considered production ready. Until then, expect it to be a building site and wear your +hard hat. + +Our goal is to cut a new milestone roughly once a month. There are no fixed dates. If need be, a milestone may slip by +a few days to ensure the code is sufficiently usable. Usually the release will happen around the end of the month. + +Steps to cut a release +====================== + +1. Pick a commit that is stable and do basic QA: run all the tests, run the demos. +2. Review the commits between this release and the last looking for new features, API changes, etc. Make sure the + summary in the current section of the :doc:`release-notes` is correct and update if not. Then move it into the right + section for this release. This is the right place to put any advice on how to port app code from the last release. +3. Additionally, if there are any new features or APIs that deserve a new section in the docsite and the author didn't + create one, bug them to do so a day or two before the release. +4. Regenerate the docsite if necessary and commit. +5. Create a branch with a name like `release-M0` where 0 is replaced by the number of the milestone. +6. Adjust the version in the root build.gradle file to take out the -SNAPSHOT and commit it on the branch. +7. Remove the "is master" warning from the docsite index page on this branch only. +8. Tag the branch with a tag like `release-M0.0` +9. Push the branch and the tag to git. +10. Write up a short announcement containing the summary of new features, changes, and API breaks. Send it to the r3dlg-awg mailing list. +11. On master, adjust the version number in the root build.gradle file upwards. + +If there are serious bugs found in the release, backport the fix to the branch and then tag it with e.g. `release-M0.1` +Minor changes to the branch don't have to be announced unless it'd be critical to get all developers updated. \ No newline at end of file diff --git a/docs/build/html/_sources/running-the-demos.txt b/docs/build/html/_sources/running-the-demos.txt new file mode 100644 index 0000000000..e6a75b6766 --- /dev/null +++ b/docs/build/html/_sources/running-the-demos.txt @@ -0,0 +1,76 @@ +Running the demos +================= + +The repository contains a small number of demo programs that run two-node networks, demonstrating functionality developed +so far. We have: + +1. The trader demo, which shows a delivery-vs-payment atomic swap of commercial paper for cash. You can learn more about + how this works in :doc:`protocol-state-machines`. +2. The IRS demo, which shows two nodes establishing an interest rate swap between them and performing fixings with a + rates oracle, all driven via the HTTP API. +3. The IRS demo web interface - a web interface to the IRS demo. +4. The attachment demo, which demonstrates uploading attachments to nodes. +5. The SIMM valuation demo, a large demo which shows two nodes agreeing on a portfolio and valuing the initial margin + using the Standard Initial Margin Model. + +.. note:: The demos currently must be run from IntelliJ, this will change before M6. + +.. note:: If any demos don't work please jump on our mailing list and let us know. + +Trader demo +----------- + +1. Open the Corda project in IntelliJ and run the "Install" configuration +2. Open the Corda samples project in IntelliJ and run the "Trader Demo: Run Nodes" configuration +3. Run "Trader Demo: Run Buyer" +4. Run "Trader Demo: Run Seller" + +In the "Trader Demo: Run Nodes" windows you should see some log lines scroll past, and within a few seconds the messages +"Purchase complete - we are a happy customer!" and "Sale completed - we have a happy customer!" should be printed. + +IRS demo +-------- + +1. Open the Corda project in IntelliJ and run the "Install" configuration +2. Open the Corda samples project in IntelliJ and run the "IRS Demo: Run Nodes" configuration +3. Run "IRS Demo: Run Upload Rates" to upload rates to the oracle. +4. Run "IRS Demo: Run Trade" to have nodes agree on a trade. +5. Run "IRS Demo: Run Date Change" to run the fixings. + +In the "IRS Demo: Run Nodes" window you'll see a lot of activity when you run the trade and when you run the date change. +The date change rolls the clock forwards and causes the nodes to agree on the fixings over a period. + +IRS web demo +------------ + +There is also an IRS web demo installed. To use this follow steps 1-3 in the IRS demo and then navigate to +http://localhost:10005/web/irsdemo and http://localhost:10005/web/irsdemo to see both node's view of the trades. + +To use the demos click the "Create Deal" button, fill in the form, then click the "Submit" button. Now you will be +able to use the time controls at the top left of the home page to run the fixings. Click any individual trade in the +blotter to view it. + +Attachment demo +--------------- + +1. Open the Corda project in IntelliJ and run the "Install" configuration +2. Open the Corda samples project in IntelliJ and run the "Attachment Demo: Run Nodes" configuration +3. Run "Attachment Demo: Run Recipient" - this waits for a trade to start +4. Run "Attachment Demo: Run Sender" - sends the attachment + +In the "Attachment Demo: Run Nodes" window you should see some log lines scroll past, and within a few seconds the +message "File received - we're happy!" should be printed. + +SIMM and Portfolio Demo +----------------------- + +.. note:: Read more about this demo at :doc:`initialmarginagreement`. + +To run the demo run: + +1. Open the Corda project in IntelliJ and run the "Install" configuration +2. Open the Corda samples project in IntelliJ and run the "Simm Valuation Demo" configuration + +Now open http://localhost:10005/web/simmvaluationdemo and http://localhost:10005/web/simmvaluationdemo to view the two nodes that this +will have started respectively. You can now use the demo by creating trades and agreeing the valuations. + diff --git a/docs/build/html/_sources/secure-coding-guidelines.txt b/docs/build/html/_sources/secure-coding-guidelines.txt new file mode 100644 index 0000000000..d3c9e26d4a --- /dev/null +++ b/docs/build/html/_sources/secure-coding-guidelines.txt @@ -0,0 +1,47 @@ +Secure coding guidelines +======================== + +The platform does what it can to be secure by default and safe by design. Unfortunately the platform cannot +prevent every kind of security mistake. This document describes what to think about when writing applications +to block various kinds of attack. Whilst it may be tempting to just assume no reasonable counterparty would +attempt to subvert your trades using protocol level attacks, relying on trust for software security makes it +harder to scale up your operations later when you might want to add counterparties quickly and without +extensive vetting. + +Protocols +--------- + +:doc:`protocol-state-machines` are how your app communicates with other parties on the network. Therefore they +are the typical entry point for malicious data into your app and must be treated with care. + +The ``receive`` methods return data wrapped in the ``UntrustworthyData`` marker type. This type doesn't add +any functionality, it's only there to remind you to properly validate everything that you get from the network. +Remember that the other side may *not* be running the code you provide to take part in the protocol: they are +allowed to do anything! Things to watch out for: + +* A transaction that doesn't match a partial transaction built or proposed earlier in the protocol, for instance, + if you propose to trade a cash state worth $100 for an asset, and the transaction to sign comes back from the + other side, you must check that it points to the state you actually requested. Otherwise the attacker could + get you to sign a transaction that spends a much larger state to you, if they know the ID of one! +* A transaction that isn't of the right type. There are two transaction types: general and notary change. If you + are expecting one type but get the other you may find yourself signing a transaction that transfers your assets + to the control of a hostile notary. +* Unexpected changes in any part of the states in a transaction. If you have access to all the needed data, you + could re-run the builder logic and do a comparison of the resulting states to ensure that it's what you expected. + For instance if the data needed to construct the next state is available to both parties, the function to + calculate the transaction you want to mutually agree could be shared between both classes implementing both + sides of the protocol. + +The theme should be clear: signing is a very sensitive operation, so you need to be sure you know what it is you +are about to sign, and that nothing has changed in the small print! + +Contracts +--------- + +Contracts are arbitrary functions inside a JVM sandbox and therefore they have a lot of leeway to shoot themselves +in the foot. Things to watch out for: + +* Changes in states that should not be allowed by the current state transition. You will want to check that no + fields are changing except the intended fields! +* Accidentally catching and discarding exceptions that might be thrown by validation logic. +* Calling into other contracts via virtual methods if you don't know what those other contracts are or might do. \ No newline at end of file diff --git a/docs/build/html/_sources/transaction-data-types.txt b/docs/build/html/_sources/transaction-data-types.txt new file mode 100644 index 0000000000..be1c082444 --- /dev/null +++ b/docs/build/html/_sources/transaction-data-types.txt @@ -0,0 +1,204 @@ +Data types +========== + +Corda provides a large standard library of data types used in financial transactions and contract state objects. +These provide a common language for states and contracts. + +Amount +------ + +The `Amount `_ class is used to represent an amount of some +fungible asset. It is a generic class which wraps around a type used to define the underlying product, called +the *token*. For instance it can be the standard JDK type ``Currency``, or an ``Issued`` instance, or this can be +a more complex type such as an obligation contract issuance definition (which in turn contains a token definition +for whatever the obligation is to be settled in). + +.. note:: Fungible is used here to mean that instances of an asset is interchangeable for any other identical instance, + and that they can be split/merged. For example a £5 note can reasonably be exchanged for any other £5 note, and a + £10 note can be exchanged for two £5 notes, or vice-versa. + +Here are some examples: + +.. container:: codeset + + .. sourcecode:: kotlin + + // A quantity of some specific currency like pounds, euros, dollars etc. + Amount + // A quantity of currency that is issued by a specific issuer, for instance central bank vs other bank dollars + Amount> + // A quantity of obligations to deliver currency of any issuer. + Amount> + +``Amount`` represents quantities as integers. For currencies the quantity represents pennies, cents or whatever +else the smallest integer amount for that currency is. You cannot use ``Amount`` to represent negative quantities +or fractional quantities: if you wish to do this then you must use a different type e.g. ``BigDecimal``. ``Amount`` +defines methods to do addition and subtraction and these methods verify that the tokens on both sides of the operator +are equal (these are operator overloads in Kotlin and can be used as regular methods from Java). There are also +methods to do multiplication and division by integer amounts. + +State +----- + +A Corda contract is composed of three parts; the executable code, the legal prose, and the state objects that represent +the details of a specific deal or asset (see :doc:`data-model` for further detail). In relational database terms +a state is like a row in a database. A reference to a state in the ledger (whether it has been consumed or not) +is represented with a ``StateRef`` object. If the state ref has been looked up from storage, you will have a +``StateAndRef`` which is simply a ``StateRef`` plus the data. + +The ``ContractState`` type is an interface that all states must implement. A ``TransactionState`` is a simple +container for a ``ContractState`` (the custom data used by a contract program) and additional platform-level state +information, such as the *notary* pointer (see :doc:`consensus`). + +A number of interfaces then extend ``ContractState``, representing standardised functionality for common kinds +of state: + + ``OwnableState`` + A state which has an owner (represented as a ``PublicKey``, discussed later). Exposes the owner and a function + for replacing the owner e.g. when an asset is sold. + + ``LinearState`` + A state which links back to its previous state, creating a thread of states over time. A linear state is + useful when modelling an indivisible/non-fungible thing like a specific deal, or an asset that can't be + split (like a rare piece of art). + + ``DealState`` + A LinearState representing an agreement between two or more parties. Intended to simplify implementing generic + protocols that manipulate many agreement types. + + ``FixableDealState`` + A deal state, with further functions exposed to support fixing of interest rates. + +NamedByHash and UniqueIdentifier +-------------------------------- + +Things which are identified by their hash, like transactions and attachments, should implement the ``NamedByHash`` +interface which standardises how the ID is extracted. Note that a hash is *not* a globally unique identifier: it +is always a derivative summary of the contents of the underlying data. Sometimes this isn't what you want: +two deals that have exactly the same parameters and which are made simultaneously but which are logically different +can't be identified by hash because their contents would be identical. Instead you would use ``UniqueIdentifier``. +This is a combination of a (Java) ``UUID`` representing a globally unique 128 bit random number, and an arbitrary +string which can be paired with it. For instance the string may represent an existing "weak" (not guaranteed unique) +identifier for convenience purposes. + +FungibleAssets and Cash +----------------------- + +There is a common ``FungibleAsset`` superclass for contracts which model fungible assets, which also provides a standard +interface for its subclasses' state objects to implement. The clear use-case is ``Cash``, however ``FungibleAsset`` is +intended to be readily extensible to cover other assets, for example commodities could be modelled by using a subclass +whose state objects include further details (location of the commodity, origin, grade, etc.) as needed. + +Transaction lifecycle types +--------------------------- + +The ``WireTransaction`` class contains the core of a transaction without signatures, and with references to attachments +in place of the attachments themselves (see also :doc:`data-model`). Once signed these are encapsulated in the +``SignedTransaction`` class. For processing a transaction (i.e. to verify it) it is first converted to a +``LedgerTransaction``, which involves verifying the signatures and associating them to the relevant command(s), and +resolving the attachment references to the attachments. Commands with valid signatures are encapsulated in the +``AuthenticatedObject`` type. + +.. note:: A ``LedgerTransaction`` has not necessarily had its contracts be run, and thus could be contract-invalid + (but not signature-invalid). You can use the ``verify`` method as shown below to run the contracts. + +When constructing a new transaction from scratch, you use ``TransactionBuilder``, which is a mutable transaction that +can be signed once modification of the internals is complete. It is typical for contract classes to expose helper +methods that can contribute to a ``TransactionBuilder``. + +Here's an example of building a transaction that creates an issuance of bananas (note that bananas are not a real +contract type in the library): + +.. container:: codeset + + .. sourcecode:: kotlin + + val notaryToUse: Party = ... + val txb = TransactionBuilder(notary = notaryToUse).withItems(BananaState(Amount(20, Bananas), fromCountry = "Elbonia")) + txb.signWith(myKey) + txb.setTime(Instant.now(), notaryToUse, 30.seconds) + // We must disable the check for sufficient signatures, because this transaction is not yet notarised. + val stx = txb.toSignedTransaction(checkSufficientSignatures = false) + // Alternatively, let's just check it verifies pretending it was fully signed. To do this, we get + // a WireTransaction, which is what the SignedTransaction wraps. Thus by verifying that directly we + // skip signature checking. + txb.toWireTransaction().toLedgerTransaction(services).verify() + +In a unit test, you would typically use a freshly created ``MockServices`` object, or more realistically, you would +write your tests using the :doc:`domain specific language for writing tests `. + +Party and PublicKey +------------------- + +Entities using the network are called *parties*. Parties can sign structures using keys, and a party may have many +keys under their control. + +Parties may sometimes be identified pseudonomously, for example, in a transaction sent to your node as part of a +chain of custody it is important you can convince yourself of the transaction's validity, but equally important that +you don't learn anything about who was involved in that transaction. In these cases a public key may be present +without any identifying information about who owns it. + +Identities of parties involved in signing a transaction can be represented simply by a ``PublicKey``, or by further +information (such as name) using the ``Party`` class. An ``AuthenticatedObject`` represents an object (like a command) +that has been signed by a set of parties. + +.. note:: These types are provisional and will change significantly in future as the identity framework becomes more + fleshed out. + +Multi-signature support +----------------------- + +Corda supports scenarios where more than one key or party is required to authorise a state object transition, for example: +"Either the CEO or 3 out of 5 of his assistants need to provide signatures". + +Key Trees +^^^^^^^^^ + +This is achieved by public key composition, using a tree data structure ``PublicKeyTree``. A ``PublicKeyTree`` stores the +cryptographic public key primitives in its leaves and the composition logic in the intermediary nodes. Every intermediary +node specifies a *threshold* of how many child signatures it requires. + +An illustration of an *"either Alice and Bob, or Charlie"* public key tree: + +.. image:: resources/public-key-tree.png +:width: 300px + +To allow further flexibility, each child node can have an associated custom *weight* (the default is 1). The *threshold* +then specifies the minimum total weight of all children required. Our previous example can also be expressed as: + +.. image:: resources/public-key-tree-2.png +:width: 300px + +Verification +^^^^^^^^^^^^ + +Signature verification is performed in two stages: + + 1. Given a list of signatures, each signature is verified against the expected content. + 2. The public keys corresponding to the signatures are matched against the leaves of the public key tree in question, + and the total combined weight of all children is calculated for every intermediary node. If all thresholds are satisfied, + the public key tree requirement is considered to be met. + +Date support +------------ + +There are a number of supporting interfaces and classes for use by contract which deal with dates (especially in the +context of deadlines). As contract negotiation typically deals with deadlines in terms such as "overnight", "T+3", +etc., it's desirable to allow conversion of these terms to their equivalent deadline. ``Tenor`` models the interval +before a deadline, such as 3 days, etc., while ``DateRollConvention`` describes how deadlines are modified to take +into account bank holidays or other events that modify normal working days. + +Calculating the rollover of a deadline based on working days requires information on the bank holidays involved +(and where a contract's parties are in different countries, for example, this can involve multiple separate sets of +bank holidays). The ``BusinessCalendar`` class models these calendars of business holidays; currently it loads these +from files on disk, but in future this is likely to involve reference data oracles in order to ensure consensus on the +dates used. + +Cryptography & maths support +---------------------------- + +The ``SecureHash`` class represents a secure hash of unknown algorithm. We currently define only a single subclass, +``SecureHash.SHA256``. There are utility methods to create them, parse them and so on. + +We also provide some mathematical utilities, in particular a set of interpolators and classes for working with +splines. These can be found in the `maths package `_. diff --git a/docs/build/html/_sources/tutorial-attachments.txt b/docs/build/html/_sources/tutorial-attachments.txt new file mode 100644 index 0000000000..b9ae8ee3fb --- /dev/null +++ b/docs/build/html/_sources/tutorial-attachments.txt @@ -0,0 +1,99 @@ +.. highlight:: kotlin +.. raw:: html + +Using attachments +================= + +Attachments are (typically large) Zip/Jar files referenced within a transaction, but not included in the transaction +itself. These files can be requested from the originating node as needed, although in many cases will be cached within +nodes already. Examples include: + +* Contract executable code +* Metadata about a transaction, such as PDF version of an invoice being settled +* Shared information to be permanently recorded on the ledger + +To add attachments the file must first be added to the node's storage service using ``StorageService.importAttachment()``, +which returns a unique ID that can be added using ``TransactionBuilder.addAttachment()``. Attachments can also be +uploaded and downloaded via HTTP, to enable integration with external systems. For instructions on HTTP upload/download +please see ":doc:`node-administration`". + +Normally attachments on transactions are fetched automatically via the ``ResolveTransactionsProtocol`` when verifying +received transactions. Attachments are needed in order to validate a transaction (they include, for example, the +contract code), so must be fetched before the validation process can run. ``ResolveTransactionsProtocol`` calls +``FetchTransactionsProtocol`` to perform the actual retrieval. + +It is encouraged that where possible attachments are reusable data, so that nodes can meaningfully cache them. + +Attachments demo +---------------- + +There is a worked example of attachments, which relays a simple document from one node to another. The "two party +trade protocol" also includes an attachment, however it is a significantly more complex demo, and less well suited +for a tutorial. + +The demo code is in the file "src/main/kotlin/net.corda.demos/attachment/AttachmentDemo.kt", with the core logic +contained within the two functions ``runRecipient()`` and ``runSender()``. We'll look at the recipient function first; +this subscribes to notifications of new validated transactions, and if it receives a transaction containing attachments, +loads the first attachment from storage, and checks it matches the expected attachment ID. ``ResolveTransactionsProtocol`` +has already fetched all attachments from the remote node, and as such the attachments are available from the node's +storage service. Once the attachment is verified, the node shuts itself down. + +.. sourcecode:: kotlin + + private fun runRecipient(node: Node) { + val serviceHub = node.services + + // Normally we would receive the transaction from a more specific protocol, but in this case we let [FinalityProtocol] + // handle receiving it for us. + serviceHub.storageService.validatedTransactions.updates.subscribe { event -> + // When the transaction is received, it's passed through [ResolveTransactionsProtocol], which first fetches any + // attachments for us, then verifies the transaction. As such, by the time it hits the validated transaction store, + // we have a copy of the attachment. + val tx = event.tx + if (tx.attachments.isNotEmpty()) { + val attachment = serviceHub.storageService.attachments.openAttachment(tx.attachments.first()) + assertEquals(PROSPECTUS_HASH, attachment?.id) + + println("File received - we're happy!\n\nFinal transaction is:\n\n${Emoji.renderIfSupported(event.tx)}") + thread { + node.stop() + } + } + } + } + +The sender correspondingly builds a transaction with the attachment, then calls ``FinalityProtocol`` to complete the +transaction and send it to the recipient node: + + +.. sourcecode:: kotlin + + private fun runSender(node: Node, otherSide: Party) { + val serviceHub = node.services + // Make sure we have the file in storage + if (serviceHub.storageService.attachments.openAttachment(PROSPECTUS_HASH) == null) { + net.corda.demos.Role::class.java.getResourceAsStream("bank-of-london-cp.jar").use { + val id = node.storage.attachments.importAttachment(it) + assertEquals(PROSPECTUS_HASH, id) + } + } + + // Create a trivial transaction that just passes across the attachment - in normal cases there would be + // inputs, outputs and commands that refer to this attachment. + val ptx = TransactionType.General.Builder(notary = null) + ptx.addAttachment(serviceHub.storageService.attachments.openAttachment(PROSPECTUS_HASH)!!.id) + + // Despite not having any states, we have to have at least one signature on the transaction + ptx.signWith(ALICE_KEY) + + // Send the transaction to the other recipient + val tx = ptx.toSignedTransaction() + serviceHub.startProtocol(LOG_SENDER, FinalityProtocol(tx, emptySet(), setOf(otherSide))).success { + thread { + Thread.sleep(1000L) // Give the other side time to request the attachment + node.stop() + } + }.failure { + println("Failed to relay message ") + } + } diff --git a/docs/build/html/_sources/tutorial-clientrpc-api.txt b/docs/build/html/_sources/tutorial-clientrpc-api.txt new file mode 100644 index 0000000000..b97c50e67d --- /dev/null +++ b/docs/build/html/_sources/tutorial-clientrpc-api.txt @@ -0,0 +1,83 @@ +.. _graphstream: http://graphstream-project.org/ + +Client RPC API +============== + +In this tutorial we will build a simple command line utility that connects to a node and dumps the transaction graph to +the standard output. We will then put some simple visualisation on top. For an explanation on how the RPC works see +:doc:`clientrpc`. + +We start off by connecting to the node itself. For the purposes of the tutorial we will run the Trader demo on some +local port and connect to the Buyer side. We will pass in the address as a command line argument. To connect to the node +we also need to access the certificates of the node, we will access the node's ``certificates`` directory directly. + +.. literalinclude:: example-code/src/main/kotlin/net.corda.docs/ClientRpcTutorial.kt + :language: kotlin + :start-after: START 1 + :end-before: END 1 + +Now we can connect to the node itself using a valid RPC login. By default the user `user1` is available with password `test`. + +.. literalinclude:: example-code/src/main/kotlin/net.corda.docs/ClientRpcTutorial.kt + :language: kotlin + :start-after: START 2 + :end-before: END 2 + +``proxy`` now exposes the full RPC interface of the node: + +.. literalinclude:: ../../node/src/main/kotlin/net.corda.node/services/messaging/CordaRPCOps.kt + :language: kotlin + :start-after: interface CordaRPCOps + :end-before: } + +The one we need in order to dump the transaction graph is ``verifiedTransactions``. The type signature tells us that the +RPC will return a list of transactions and an Observable stream. This is a general pattern, we query some data and the +node will return the current snapshot and future updates done to it. + +.. literalinclude:: example-code/src/main/kotlin/net.corda.docs/ClientRpcTutorial.kt + :language: kotlin + :start-after: START 3 + :end-before: END 3 + +The graph will be defined by nodes and edges between them. Each node represents a transaction and edges represent +output-input relations. For now let's just print ``NODE `` for the former and ``EDGE `` for the +latter. + +.. literalinclude:: example-code/src/main/kotlin/net.corda.docs/ClientRpcTutorial.kt + :language: kotlin + :start-after: START 4 + :end-before: END 4 + +Now we can start the trader demo as per described in :doc:`running-the-demos`:: + + # Build the demo + ./gradlew installDist + # Start the buyer + ./build/install/r3prototyping/bin/trader-demo --role=BUYER + +In another terminal we can connect to it with our client:: + + # Connect to localhost:31337 + ./docs/source/example-code/build/install/docs/source/example-code/bin/client-rpc-tutorial localhost:31337 Print + +We should see some ``NODE``-s printed. This is because the buyer self-issues some cash for the demo. +Unless we ran the seller before we shouldn't see any ``EDGE``-s because the cash hasn't been spent yet. + +In another terminal we can now start the seller:: + + # Start sellers in a loop + for i in {0..9} ; do ./build/install/r3prototyping/bin/trader-demo --role=SELLER ; done + +We should start seeing new ``NODE``-s and ``EDGE``-s appearing. + +Now let's try to visualise the transaction graph. We will use a graph drawing library called graphstream_ + +.. literalinclude:: example-code/src/main/kotlin/net.corda.docs/ClientRpcTutorial.kt + :language: kotlin + :start-after: START 5 + :end-before: END 5 + +If we run the client with ``Visualise`` we should see a simple graph being drawn as new transactions are being created +by the seller runs. + +That's it! We saw how to connect to the node and stream data from it. diff --git a/docs/build/html/_sources/tutorial-contract-clauses.txt b/docs/build/html/_sources/tutorial-contract-clauses.txt new file mode 100644 index 0000000000..895ff0d964 --- /dev/null +++ b/docs/build/html/_sources/tutorial-contract-clauses.txt @@ -0,0 +1,194 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Writing a contract using clauses +================================ + +This tutorial will take you through restructuring the commercial paper contract to use clauses. You should have +already completed ":doc:`tutorial-contract`". + +Clauses are essentially micro-contracts which contain independent verification logic, and can be logically composed +together to form a contract. Clauses are designed to enable re-use of common logic, for example issuing state objects +is generally the same for all fungible contracts, so a common issuance clause can be inherited for each contract's +issue clause. This cuts down on scope for error, and improves consistency of behaviour. By splitting verification logic +into smaller chunks, they can also be readily tested in isolation. + +Clauses can be composed of subclauses, for example the ``AllClause`` or ``AnyClause`` clauses take list of clauses +that they delegate to. Clauses can also change the scope of states and commands being verified, for example grouping +together fungible state objects and running a clause against each distinct group. + +The commercial paper contract has a ``Group`` outermost clause, which contains the ``Issue``, ``Move`` and ``Redeem`` +clauses. The result is a contract that looks something like this: + + 1. Group input and output states together, and then apply the following clauses on each group: + a. If an ``Issue`` command is present, run appropriate tests and end processing this group. + b. If a ``Move`` command is present, run appropriate tests and end processing this group. + c. If a ``Redeem`` command is present, run appropriate tests and end processing this group. + +Commercial paper class +---------------------- + +To use the clause verification logic, the contract needs to call the ``verifyClause`` function, passing in the +transaction, a clause to verify, and a collection of commands the clauses are expected to handle all of. This list of +commands is important because ``verifyClause`` checks that none of the commands are left unprocessed at the end, and +raises an error if they are. The top level clause would normally be a composite clause (such as ``AnyComposition``, +``AllComposition``, etc.) which contains further clauses. The following examples are trimmed to the modified class +definition and added elements, for brevity: + +.. container:: codeset + + .. sourcecode:: kotlin + + class CommercialPaper : Contract { + override val legalContractReference: SecureHash = SecureHash.sha256("https://en.wikipedia.org/wiki/Commercial_paper") + + override fun verify(tx: TransactionForContract) = verifyClause(tx, Clauses.Group(), tx.commands.select()) + + .. sourcecode:: java + + public class CommercialPaper implements Contract { + @Override + public SecureHash getLegalContractReference() { + return SecureHash.Companion.sha256("https://en.wikipedia.org/wiki/Commercial_paper"); + } + + @Override + public void verify(@NotNull TransactionForContract tx) throws IllegalArgumentException { + ClauseVerifier.verifyClause(tx, new Clauses.Group(), extractCommands(tx)); + } + +Clauses +------- + +We'll tackle the inner clauses that contain the bulk of the verification logic, first, and the clause which handles +grouping of input/output states later. The clauses must extend the ``Clause`` abstract class, which defines +the ``verify`` function, and the ``requiredCommands`` property used to determine the conditions under which a clause +is triggered. Composite clauses should extend the ``CompositeClause`` abstract class, which extends ``Clause`` to +add support for wrapping around multiple clauses. + +The ``verify`` function defined in the ``Clause`` interface is similar to the conventional ``Contract`` verification +function, although it adds new parameters and returns the set of commands which it has processed. Normally this returned +set is identical to the ``requiredCommands`` used to trigger the clause, however in some cases the clause may process +further optional commands which it needs to report that it has handled. + +The ``Move`` clause for the commercial paper contract is relatively simple, so we will start there: + +.. container:: codeset + + .. sourcecode:: kotlin + + class Move: Clause>() { + override val requiredCommands: Set> + get() = setOf(Commands.Move::class.java) + + override fun verify(tx: TransactionForContract, + inputs: List, + outputs: List, + commands: List>, + groupingKey: Issued?): Set { + val command = commands.requireSingleCommand() + val input = inputs.single() + requireThat { + "the transaction is signed by the owner of the CP" by (input.owner in command.signers) + "the state is propagated" by (outputs.size == 1) + // Don't need to check anything else, as if outputs.size == 1 then the output is equal to + // the input ignoring the owner field due to the grouping. + } + return setOf(command.value) + } + } + + .. sourcecode:: java + + class Move extends Clause { + @NotNull + @Override + public Set> getRequiredCommands() { + return Collections.singleton(Commands.Move.class); + } + + @NotNull + @Override + public Set verify(@NotNull TransactionForContract tx, + @NotNull List inputs, + @NotNull List outputs, + @NotNull List> commands, + @NotNull State groupingKey) { + AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.Move.class); + // There should be only a single input due to aggregation above + State input = single(inputs); + + if (!cmd.getSigners().contains(input.getOwner())) + throw new IllegalStateException("Failed requirement: the transaction is signed by the owner of the CP"); + + // Check the output CP state is the same as the input state, ignoring the owner field. + if (outputs.size() != 1) { + throw new IllegalStateException("the state is propagated"); + } + // Don't need to check anything else, as if outputs.size == 1 then the output is equal to + // the input ignoring the owner field due to the grouping. + return Collections.singleton(cmd.getValue()); + } + } + +Group Clause +------------ + +We need to wrap the move clause (as well as the issue and redeem clauses - see the relevant contract code for their +full specifications) in an outer clause that understands how to group contract states and objects. For this we extend +the standard ``GroupClauseVerifier`` and specify how to group input/output states, as well as the top-level to run on +each group. As with the top level clause on a contract, this is normally a composite clause that delegates to subclauses. + + +.. container:: codeset + + .. sourcecode:: kotlin + + class Group : GroupClauseVerifier>( + AnyComposition( + Redeem(), + Move(), + Issue())) { + override fun groupStates(tx: TransactionForContract): List>> + = tx.groupStates> { it.token } + } + + .. sourcecode:: java + + class Group extends GroupClauseVerifier { + public Group() { + super(new AnyComposition<>( + new Clauses.Redeem(), + new Clauses.Move(), + new Clauses.Issue() + )); + } + + @NotNull + @Override + public List> groupStates(@NotNull TransactionForContract tx) { + return tx.groupStates(State.class, State::withoutOwner); + } + } + +For the ``CommercialPaper`` contract, this is the top level clause for the contract, and is passed directly into +``verifyClause`` (see the example code at the top of this tutorial). + +Summary +------- + +In summary the top level contract ``CommercialPaper`` specifies a single grouping clause of type +``CommercialPaper.Clauses.Group`` which in turn specifies ``GroupClause`` implementations for each type of command +(``Redeem``, ``Move`` and ``Issue``). This reflects the flow of verification: In order to verify a ``CommercialPaper`` +we first group states, check which commands are specified, and run command-specific verification logic accordingly. + +Debugging +--------- + +Debugging clauses which have been composed together can be complicated due to the difficulty in knowing which clauses +have been matched, whether specific clauses failed to match or passed verification, etc. There is "trace" level +logging code in the clause verifier which evaluates which clauses will be matched and logs them, before actually +performing the validation. To enable this, ensure trace level logging is enabled on the ``Clause`` interface. diff --git a/docs/build/html/_sources/tutorial-contract.txt b/docs/build/html/_sources/tutorial-contract.txt new file mode 100644 index 0000000000..c7b05f0a6e --- /dev/null +++ b/docs/build/html/_sources/tutorial-contract.txt @@ -0,0 +1,803 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Writing a contract +================== + +This tutorial will take you through how the commercial paper contract works. This uses a simple contract structure of +everything being in one contract class, while most actual contracts in Corda are broken into clauses (which we'll +discuss in the next tutorial). Clauses help reduce tedious boilerplate, but it's worth understanding how a +contract is built without them before starting. + +You can see the full Kotlin version of this contract in the code as ``CommercialPaperLegacy``. The code in this +tutorial is available in both Kotlin and Java. You can quickly switch between them to get a feeling for how +Kotlin syntax works. + +Where to put your code +---------------------- + +A CorDapp is a collection of contracts, state definitions, protocols and other ways to extend the server. To create +one you would just create a Java-style project as normal, with your choice of build system (Maven, Gradle, etc). +Then add a dependency on ``net.corda.core:0.X`` where X is the milestone number you are depending on. The core +module defines the base classes used in this tutorial. + +Starting the commercial paper class +----------------------------------- + +A smart contract is a class that implements the ``Contract`` interface. This can be either implemented directly, or +by subclassing an abstract contract such as ``OnLedgerAsset``. + +.. container:: codeset + + .. sourcecode:: kotlin + + class CommercialPaper : Contract { + override val legalContractReference: SecureHash = SecureHash.sha256("https://en.wikipedia.org/wiki/Commercial_paper"); + + override fun verify(tx: TransactionForVerification) { + TODO() + } + } + + .. sourcecode:: java + + public class CommercialPaper implements Contract { + @Override + public SecureHash getLegalContractReference() { + return SecureHash.Companion.sha256("https://en.wikipedia.org/wiki/Commercial_paper"); + } + + @Override + public void verify(TransactionForVerification tx) { + throw new UnsupportedOperationException(); + } + } + +Every contract must have at least a ``getLegalContractReference()`` and a ``verify()`` method. In Kotlin we express +a getter without a setter as an immutable property (val). The *legal contract reference* is supposed to be a hash +of a document that describes the legal contract and may take precedence over the code, in case of a dispute. + +.. note:: The way legal contract prose is bound to a smart contract implementation will change in future. + +The verify method returns nothing. This is intentional: the function either completes correctly, or throws an exception, +in which case the transaction is rejected. + +So far, so simple. Now we need to define the commercial paper *state*, which represents the fact of ownership of a +piece of issued paper. + +States +------ + +A state is a class that stores data that is checked by the contract. + +.. container:: codeset + + .. sourcecode:: kotlin + + data class State( + val issuance: PartyAndReference, + override val owner: PublicKey, + val faceValue: Amount>, + val maturityDate: Instant + ) : OwnableState { + override val contract = CommercialPaper() + override val participants = listOf(owner) + + fun withoutOwner() = copy(owner = NullPublicKey) + override fun withNewOwner(newOwner: PublicKey) = Pair(Commands.Move(), copy(owner = newOwner)) + } + + .. sourcecode:: java + + public static class State implements OwnableState { + private PartyAndReference issuance; + private PublicKey owner; + private Amount> faceValue; + private Instant maturityDate; + + public State() { + } // For serialization + + public State(PartyAndReference issuance, PublicKey owner, Amount> faceValue, + Instant maturityDate) { + this.issuance = issuance; + this.owner = owner; + this.faceValue = faceValue; + this.maturityDate = maturityDate; + } + + public State copy() { + return new State(this.issuance, this.owner, this.faceValue, this.maturityDate); + } + + @NotNull + @Override + public Pair withNewOwner(@NotNull PublicKey newOwner) { + return new Pair<>(new Commands.Move(), new State(this.issuance, newOwner, this.faceValue, this.maturityDate)); + } + + public PartyAndReference getIssuance() { + return issuance; + } + + public PublicKey getOwner() { + return owner; + } + + public Amount> getFaceValue() { + return faceValue; + } + + public Instant getMaturityDate() { + return maturityDate; + } + + @NotNull + @Override + public Contract getContract() { + return new JavaCommercialPaper(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + State state = (State) o; + + if (issuance != null ? !issuance.equals(state.issuance) : state.issuance != null) return false; + if (owner != null ? !owner.equals(state.owner) : state.owner != null) return false; + if (faceValue != null ? !faceValue.equals(state.faceValue) : state.faceValue != null) return false; + return !(maturityDate != null ? !maturityDate.equals(state.maturityDate) : state.maturityDate != null); + } + + @Override + public int hashCode() { + int result = issuance != null ? issuance.hashCode() : 0; + result = 31 * result + (owner != null ? owner.hashCode() : 0); + result = 31 * result + (faceValue != null ? faceValue.hashCode() : 0); + result = 31 * result + (maturityDate != null ? maturityDate.hashCode() : 0); + return result; + } + + @NotNull + @Override + public List getParticipants() { + return ImmutableList.of(this.owner); + } + } + + +We define a class that implements the ``ContractState`` interface. + +The ``ContractState`` interface requires us to provide a ``getContract`` method that returns an instance of the +contract class itself. In future, this will change to support dynamic loading of contracts with versioning +and signing constraints, but for now this is how it's written. + +We have four fields in our state: + +* ``issuance``, a reference to a specific piece of commercial paper issued by some party. +* ``owner``, the public key of the current owner. This is the same concept as seen in Bitcoin: the public key has no + attached identity and is expected to be one-time-use for privacy reasons. However, unlike in Bitcoin, we model + ownership at the level of individual states rather than as a platform-level concept as we envisage many + (possibly most) contracts on the platform will not represent "owner/issuer" relationships, but "party/party" + relationships such as a derivative contract. +* ``faceValue``, an ``Amount>``, which wraps an integer number of pennies and a currency that is + specific to some issuer (e.g. a regular bank, a central bank, etc). You can read more about this very common + type in :doc:`transaction-data-types`. +* ``maturityDate``, an `Instant `_, which is a type + from the Java 8 standard time library. It defines a point on the timeline. + +States are immutable, and thus the class is defined as immutable as well. The ``data`` modifier in the Kotlin version +causes the compiler to generate the equals/hashCode/toString methods automatically, along with a copy method that can +be used to create variants of the original object. Data classes are similar to case classes in Scala, if you are +familiar with that language. The ``withoutOwner`` method uses the auto-generated copy method to return a version of +the state with the owner public key blanked out: this will prove useful later. + +The Java code compiles to almost identical bytecode as the Kotlin version, but as you can see, is much more verbose. + +Commands +-------- + +The logic for a contract may vary depending on what stage of a lifecycle it is automating. So it can be useful to +pass additional data into the contract code that isn't represented by the states which exist permanently in the ledger. + +For this purpose we have commands. Often they don't need to contain any data at all, they just need to exist. A command +is a piece of data associated with some *signatures*. By the time the contract runs the signatures have already been +checked, so from the contract code's perspective, a command is simply a data structure with a list of attached +public keys. Each key had a signature proving that the corresponding private key was used to sign. Because of this +approach contracts never actually interact or work with digital signatures directly. + +Let's define a few commands now: + +.. container:: codeset + + .. sourcecode:: kotlin + + interface Commands : CommandData { + class Move : TypeOnlyCommandData(), Commands + class Redeem : TypeOnlyCommandData(), Commands + class Issue : TypeOnlyCommandData(), Commands + } + + + .. sourcecode:: java + + public static class Commands implements core.contract.Command { + public static class Move extends Commands { + @Override + public boolean equals(Object obj) { + return obj instanceof Move; + } + } + + public static class Redeem extends Commands { + @Override + public boolean equals(Object obj) { + return obj instanceof Redeem; + } + } + + public static class Issue extends Commands { + @Override + public boolean equals(Object obj) { + return obj instanceof Issue; + } + } + } + +We define a simple grouping interface or static class, this gives us a type that all our commands have in common, +then we go ahead and create three commands: ``Move``, ``Redeem``, ``Issue``. ``TypeOnlyCommandData`` is a helpful utility +for the case when there's no data inside the command; only the existence matters. It defines equals and hashCode +such that any instances always compare equal and hash to the same value. + +The verify function +------------------- + +The heart of a smart contract is the code that verifies a set of state transitions (a *transaction*). The function is +simple: it's given a class representing the transaction, and if the function returns then the transaction is considered +acceptable. If it throws an exception, the transaction is rejected. + +Each transaction can have multiple input and output states of different types. The set of contracts to run is decided +by taking the code references inside each state. Each contract is run only once. As an example, a contract that includes +2 cash states and 1 commercial paper state as input, and has as output 1 cash state and 1 commercial paper state, will +run two contracts one time each: Cash and CommercialPaper. + +.. container:: codeset + + .. sourcecode:: kotlin + + override fun verify(tx: TransactionForContract) { + // Group by everything except owner: any modification to the CP at all is considered changing it fundamentally. + val groups = tx.groupStates(State::withoutOwner) + + // There are two possible things that can be done with this CP. The first is trading it. The second is redeeming + // it for cash on or after the maturity date. + val command = tx.commands.requireSingleCommand() + + .. sourcecode:: java + + @Override + public void verify(TransactionForContract tx) { + List> groups = tx.groupStates(State.class, State::withoutOwner); + AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.class); + +We start by using the ``groupStates`` method, which takes a type and a function. State grouping is a way of ensuring +your contract can handle multiple unrelated states of the same type in the same transaction, which is needed for +splitting/merging of assets, atomic swaps and so on. More on this next. + +The second line does what the code suggests: it searches for a command object that inherits from the +``CommercialPaper.Commands`` supertype, and either returns it, or throws an exception if there's zero or more than one +such command. + +Using state groups +------------------ + +The simplest way to write a smart contract would be to say that each transaction can have a single input state and a +single output state of the kind govered by that contract. This would be easy for the developer, but would prevent many +important use cases. + +The next easiest way to write a contract would be to iterate over each input state and expect it to have an output +state. Now you can build a single transaction that, for instance, moves two different cash states in different currencies +simultaneously. But it gets complicated when you want to issue or exit one state at the same time as moving another. + +Things get harder still once you want to split and merge states. We say states are *fungible* if they are +treated identically to each other by the recipient, despite the fact that they aren't quite identical. Dollar bills are +fungible because even though one may be worn/a bit dirty and another may be crisp and new, they are still both worth +exactly $1. Likewise, ten $1 bills are almost exactly equivalent to one $10 bill. On the other hand, $10 and £10 are not +fungible: if you tried to pay for something that cost £20 with $10+£10 notes your trade would not be accepted. + +To make all this easier the contract API provides a notion of groups. A group is a set of input states and output states +that should be checked for validity together. + +Consider the following simplified currency trade transaction: + +* **Input**: $12,000 owned by Alice (A) +* **Input**: $3,000 owned by Alice (A) +* **Input**: £10,000 owned by Bob (B) +* **Output**: £10,000 owned by Alice (B) +* **Output**: $15,000 owned by Bob (A) + +In this transaction Alice and Bob are trading $15,000 for £10,000. Alice has her money in the form of two different +inputs e.g. because she received the dollars in two payments. The input and output amounts do balance correctly, but +the cash smart contract must consider the pounds and the dollars separately because they are not fungible: they cannot +be merged together. So we have two groups: A and B. + +The ``TransactionForContract.groupStates`` method handles this logic for us: firstly, it selects only states of the +given type (as the transaction may include other types of state, such as states representing bond ownership, or a +multi-sig state) and then it takes a function that maps a state to a grouping key. All states that share the same key are +grouped together. In the case of the cash example above, the grouping key would be the currency. + +In this kind of contract we don't want CP to be fungible: merging and splitting is (in our example) not allowed. +So we just use a copy of the state minus the owner field as the grouping key. + +Here are some code examples: + +.. container:: codeset + + .. sourcecode:: kotlin + + // Type of groups is List>> + val groups = tx.groupStates() { it: Cash.State -> Pair(it.deposit, it.amount.currency) } + for ((inputs, outputs, key) in groups) { + // Either inputs or outputs could be empty. + val (deposit, currency) = key + + ... + } + + .. sourcecode:: java + + List>> groups = tx.groupStates(Cash.State.class, s -> Pair(s.deposit, s.amount.currency)) + for (InOutGroup> group : groups) { + List inputs = group.getInputs(); + List outputs = group.getOutputs(); + Pair key = group.getKey(); + + ... + } + +The ``groupStates`` call uses the provided function to calculate a "grouping key". All states that have the same +grouping key are placed in the same group. A grouping key can be anything that implements equals/hashCode, but it's +always an aggregate of the fields that shouldn't change between input and output. In the above example we picked the +fields we wanted and packed them into a ``Pair``. It returns a list of ``InOutGroup``, which is just a holder for the +inputs, outputs and the key that was used to define the group. In the Kotlin version we unpack these using destructuring +to get convenient access to the inputs, the outputs, the deposit data and the currency. The Java version is more +verbose, but equivalent. + +The rules can then be applied to the inputs and outputs as if it were a single transaction. A group may have zero +inputs or zero outputs: this can occur when issuing assets onto the ledger, or removing them. + +In this example, we do it differently and use the state class itself as the aggregator. We just +blank out fields that are allowed to change, making the grouping key be "everything that isn't that": + +.. container:: codeset + + .. sourcecode:: kotlin + + val groups = tx.groupStates() { it: State -> it.withoutOwner() } + + .. sourcecode:: java + + List> groups = tx.groupStates(State.class, State::withoutOwner); + +For large states with many fields that must remain constant and only one or two that are really mutable, it's often +easier to do things this way than to specifically name each field that must stay the same. The ``withoutOwner`` function +here simply returns a copy of the object but with the ``owner`` field set to ``NullPublicKey``, which is just a public key +of all zeros. It's invalid and useless, but that's OK, because all we're doing is preventing the field from mattering +in equals and hashCode. + + +Checking the requirements +------------------------- + +After extracting the command and the groups, we then iterate over each group and verify it meets the required business +logic. + +.. container:: codeset + + .. sourcecode:: kotlin + + val timestamp: Timestamp? = tx.timestamp + + for ((inputs, outputs, key) in groups) { + when (command.value) { + is Commands.Move -> { + val input = inputs.single() + requireThat { + "the transaction is signed by the owner of the CP" by (input.owner in command.signers) + "the state is propagated" by (group.outputs.size == 1) + // Don't need to check anything else, as if outputs.size == 1 then the output is equal to + // the input ignoring the owner field due to the grouping. + } + } + + is Commands.Redeem -> { + // Redemption of the paper requires movement of on-ledger cash. + val input = inputs.single() + val received = tx.outputs.sumCashBy(input.owner) + val time = timestamp?.after ?: throw IllegalArgumentException("Redemptions must be timestamped") + requireThat { + "the paper must have matured" by (time >= input.maturityDate) + "the received amount equals the face value" by (received == input.faceValue) + "the paper must be destroyed" by outputs.isEmpty() + "the transaction is signed by the owner of the CP" by (input.owner in command.signers) + } + } + + is Commands.Issue -> { + val output = outputs.single() + val time = timestamp?.before ?: throw IllegalArgumentException("Issuances must be timestamped") + requireThat { + // Don't allow people to issue commercial paper under other entities identities. + "output states are issued by a command signer" by (output.issuance.party.owningKey in command.signers) + "output values sum to more than the inputs" by (output.faceValue.quantity > 0) + "the maturity date is not in the past" by (time < output.maturityDate) + // Don't allow an existing CP state to be replaced by this issuance. + "can't reissue an existing state" by inputs.isEmpty() + } + } + + else -> throw IllegalArgumentException("Unrecognised command") + } + } + + .. sourcecode:: java + + Timestamp time = tx.getTimestamp(); // Can be null/missing. + for (InOutGroup group : groups) { + List inputs = group.getInputs(); + List outputs = group.getOutputs(); + + // For now do not allow multiple pieces of CP to trade in a single transaction. Study this more! + State input = single(filterIsInstance(inputs, State.class)); + + checkState(cmd.getSigners().contains(input.getOwner()), "the transaction is signed by the owner of the CP"); + + if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Move) { + checkState(outputs.size() == 1, "the state is propagated"); + // Don't need to check anything else, as if outputs.size == 1 then the output is equal to + // the input ignoring the owner field due to the grouping. + } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Redeem) { + checkNotNull(timem "must be timestamped"); + Instant t = time.getBefore(); + Amount> received = CashKt.sumCashBy(tx.getOutputs(), input.getOwner()); + + checkState(received.equals(input.getFaceValue()), "received amount equals the face value"); + checkState(t.isBefore(input.getMaturityDate(), "the paper must have matured"); + checkState(outputs.isEmpty(), "the paper must be destroyed"); + } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Issue) { + // .. etc .. (see Kotlin for full definition) + } + } + +This loop is the core logic of the contract. + +The first line simply gets the timestamp out of the transaction. Timestamping of transactions is optional, so a time +may be missing here. We check for it being null later. + +.. note:: In future timestamping may be mandatory for all transactions. + +.. warning:: In the Kotlin version as long as we write a comparison with the transaction time first the compiler will + verify we didn't forget to check if it's missing. Unfortunately due to the need for smooth Java interop, this + check won't happen if we write e.g. ``someDate > time``, it has to be ``time < someDate``. So it's good practice to + always write the transaction timestamp first. + +The first line (first three lines in Java) impose a requirement that there be a single piece of commercial paper in +this group. We do not allow multiple units of CP to be split or merged even if they are owned by the same owner. The +``single()`` method is a static *extension method* defined by the Kotlin standard library: given a list, it throws an +exception if the list size is not 1, otherwise it returns the single item in that list. In Java, this appears as a +regular static method of the type familiar from many FooUtils type singleton classes and we have statically imported it +here. In Kotlin, it appears as a method that can be called on any JDK list. The syntax is slightly different but +behind the scenes, the code compiles to the same bytecodes. + +Next, we check that the transaction was signed by the public key that's marked as the current owner of the commercial +paper. Because the platform has already verified all the digital signatures before the contract begins execution, +all we have to do is verify that the owner's public key was one of the keys that signed the transaction. The Java code +is straightforward: we are simply using the ``Preconditions.checkState`` method from Guava. The Kotlin version looks a little odd: we have a *requireThat* construct that looks like it's +built into the language. In fact *requireThat* is an ordinary function provided by the platform's contract API. Kotlin +supports the creation of *domain specific languages* through the intersection of several features of the language, and +we use it here to support the natural listing of requirements. To see what it compiles down to, look at the Java version. +Each ``"string" by (expression)`` statement inside a ``requireThat`` turns into an assertion that the given expression is +true, with an ``IllegalStateException`` being thrown that contains the string if not. It's just another way to write out a regular +assertion, but with the English-language requirement being put front and center. + +Next, we take one of two paths, depending on what the type of the command object is. + +If the command is a ``Move`` command, then we simply verify that the output state is actually present: a move is not +allowed to delete the CP from the ledger. The grouping logic already ensured that the details are identical and haven't +been changed, save for the public key of the owner. + +If the command is a ``Redeem`` command, then the requirements are more complex: + +1. We want to see that the face value of the CP is being moved as a cash claim against some party, that is, the + issuer of the CP is really paying back the face value. +2. The transaction must be happening after the maturity date. +3. The commercial paper must *not* be propagated by this transaction: it must be deleted, by the group having no + output state. This prevents the same CP being considered redeemable multiple times. + +To calculate how much cash is moving, we use the ``sumCashBy`` utility function. Again, this is an extension function, +so in Kotlin code it appears as if it was a method on the ``List`` type even though JDK provides no such +method. In Java we see its true nature: it is actually a static method named ``CashKt.sumCashBy``. This method simply +returns an ``Amount`` object containing the sum of all the cash states in the transaction outputs that are owned by +that given public key, or throws an exception if there were no such states *or* if there were different currencies +represented in the outputs! So we can see that this contract imposes a limitation on the structure of a redemption +transaction: you are not allowed to move currencies in the same transaction that the CP does not involve. This +limitation could be addressed with better APIs, if it were to be a real limitation. + +Finally, we support an ``Issue`` command, to create new instances of commercial paper on the ledger. It likewise +enforces various invariants upon the issuance. + +This contract is simple and does not implement all the business logic a real commercial paper lifecycle +management program would. For instance, there is no logic requiring a signature from the issuer for redemption: +it is assumed that any transfer of money that takes place at the same time as redemption is good enough. Perhaps +that is something that should be tightened. Likewise, there is no logic handling what happens if the issuer has gone +bankrupt, if there is a dispute, and so on. + +As the prototype evolves, these requirements will be explored and this tutorial updated to reflect improvements in the +contracts API. + +How to test your contract +------------------------- + +Of course, it is essential to unit test your new nugget of business logic to ensure that it behaves as you expect. +As contract code is just a regular Java function you could write out the logic entirely by hand in the usual +manner. But this would be inconvenient, and then you'd get bored of writing tests and that would be bad: you +might be tempted to skip a few. + +To make contract testing more convenient Corda provides a language-like API for both Kotlin and Java that lets +you easily construct chains of transactions and verify that they either pass validation, or fail with a particular +error message. + +Testing contracts with this domain specific language is covered in the separate tutorial, :doc:`tutorial-test-dsl`. + + +Adding a generation API to your contract +---------------------------------------- + +Contract classes **must** provide a verify function, but they may optionally also provide helper functions to simplify +their usage. A simple class of functions most contracts provide are *generation functions*, which either create or +modify a transaction to perform certain actions (an action is normally mappable 1:1 to a command, but doesn't have to +be so). + +Generation may involve complex logic. For example, the cash contract has a ``generateSpend`` method that is given a set of +cash states and chooses a way to combine them together to satisfy the amount of money that is being sent. In the +immutable-state model that we are using ledger entries (states) can only be created and deleted, but never modified. +Therefore to send $1200 when we have only $900 and $500 requires combining both states together, and then creating +two new output states of $1200 and $200 back to ourselves. This latter state is called the *change* and is a concept +that should be familiar to anyone who has worked with Bitcoin. + +As another example, we can imagine code that implements a netting algorithm may generate complex transactions that must +be signed by many people. Whilst such code might be too big for a single utility method (it'd probably be sized more +like a module), the basic concept is the same: preparation of a transaction using complex logic. + +For our commercial paper contract however, the things that can be done with it are quite simple. Let's start with +a method to wrap up the issuance process: + +.. container:: codeset + + .. sourcecode:: kotlin + + fun generateIssue(issuance: PartyAndReference, faceValue: Amount>, maturityDate: Instant, + notary: Party): TransactionBuilder { + val state = State(issuance, issuance.party.owningKey, faceValue, maturityDate) + return TransactionBuilder(notary = notary).withItems(state, Command(Commands.Issue(), issuance.party.owningKey)) + } + +We take a reference that points to the issuing party (i.e. the caller) and which can contain any internal +bookkeeping/reference numbers that we may require. The reference field is an ideal place to put (for example) a +join key. Then the face value of the paper, and the maturity date. It returns a ``TransactionBuilder``. +A ``TransactionBuilder`` is one of the few mutable classes the platform provides. It allows you to add inputs, +outputs and commands to it and is designed to be passed around, potentially between multiple contracts. + +.. note:: Generation methods should ideally be written to compose with each other, that is, they should take a + ``TransactionBuilder`` as an argument instead of returning one, unless you are sure it doesn't make sense to + combine this type of transaction with others. In this case, issuing CP at the same time as doing other things + would just introduce complexity that isn't likely to be worth it, so we return a fresh object each time: instead, + an issuer should issue the CP (starting out owned by themselves), and then sell it in a separate transaction. + +The function we define creates a ``CommercialPaper.State`` object that mostly just uses the arguments we were given, +but it fills out the owner field of the state to be the same public key as the issuing party. + +The returned partial transaction has a ``Command`` object as a parameter. This is a container for any object +that implements the ``CommandData`` interface, along with a list of keys that are expected to sign this transaction. In this case, +issuance requires that the issuing party sign, so we put the key of the party there. + +The ``TransactionBuilder`` has a convenience ``withItems`` method that takes a variable argument list. You can pass in +any ``StateAndRef`` (input), ``ContractState`` (output) or ``Command`` objects and it'll build up the transaction +for you. + +There's one final thing to be aware of: we ask the caller to select a *notary* that controls this state and +prevents it from being double spent. You can learn more about this topic in the :doc:`consensus` article. + +.. note:: For now, don't worry about how to pick a notary. More infrastructure will come later to automate this + decision for you. + +What about moving the paper, i.e. reassigning ownership to someone else? + +.. container:: codeset + + .. sourcecode:: kotlin + + fun generateMove(tx: TransactionBuilder, paper: StateAndRef, newOwner: PublicKey) { + tx.addInputState(paper) + tx.addOutputState(paper.state.data.withOwner(newOwner)) + tx.addCommand(Command(Commands.Move(), paper.state.data.owner)) + } + +Here, the method takes a pre-existing ``TransactionBuilder`` and adds to it. This is correct because typically +you will want to combine a sale of CP atomically with the movement of some other asset, such as cash. So both +generate methods should operate on the same transaction. You can see an example of this being done in the unit tests +for the commercial paper contract. + +The paper is given to us as a ``StateAndRef`` object. This is exactly what it sounds like: +a small object that has a (copy of) a state object, and also the (txhash, index) that indicates the location of this +state on the ledger. + +We add the existing paper state as an input, the same paper state with the owner field adjusted as an output, +and finally a move command that has the old owner's public key: this is what forces the current owner's signature +to be present on the transaction, and is what's checked by the contract. + +Finally, we can do redemption. + +.. container:: codeset + + .. sourcecode:: kotlin + + @Throws(InsufficientBalanceException::class) + fun generateRedeem(tx: TransactionBuilder, paper: StateAndRef, wallet: Wallet) { + // Add the cash movement using the states in our wallet. + Cash().generateSpend(tx, paper.state.data.faceValue.withoutIssuer(), paper.state.data.owner, wallet.statesOfType()) + tx.addInputState(paper) + tx.addCommand(Command(Commands.Redeem(), paper.state.data.owner)) + } + +Here we can see an example of composing contracts together. When an owner wishes to redeem the commercial paper, the +issuer (i.e. the caller) must gather cash from its wallet and send the face value to the owner of the paper. + +.. note:: This contract has no explicit concept of rollover. + +The *wallet* is a concept that may be familiar from Bitcoin and Ethereum. It is simply a set of states (such as cash) that are +owned by the caller. Here, we use the wallet to update the partial transaction we are handed with a movement of cash +from the issuer of the commercial paper to the current owner. If we don't have enough quantity of cash in our wallet, +an exception is thrown. Then we add the paper itself as an input, but, not an output (as we wish to remove it +from the ledger). Finally, we add a Redeem command that should be signed by the owner of the commercial paper. + +.. warning:: The amount we pass to the ``generateSpend`` function has to be treated first with ``withoutIssuer``. + This reflects the fact that the way we handle issuer constraints is still evolving; the commercial paper + contract requires payment in the form of a currency issued by a specific party (e.g. the central bank, + or the issuers own bank perhaps). But the wallet wants to assemble spend transactions using cash states from + any issuer, thus we must strip it here. This represents a design mismatch that we will resolve in future + versions with a more complete way to express issuer constraints. + +A ``TransactionBuilder`` is not by itself ready to be used anywhere, so first, we must convert it to something that +is recognised by the network. The most important next step is for the participating entities to sign it using the +``signWith()`` method. This takes a keypair, serialises the transaction, signs the serialised form and then stores the +signature inside the ``TransactionBuilder``. Once all parties have signed, you can call ``TransactionBuilder.toSignedTransaction()`` +to get a ``SignedTransaction`` object. + +You can see how transactions flow through the different stages of construction by examining the commercial paper +unit tests. + +How multi-party transactions are constructed and transmitted +------------------------------------------------------------ + +OK, so now we know how to define the rules of the ledger, and we know how to construct transactions that satisfy +those rules ... and if all we were doing was maintaining our own data that might be enough. But we aren't: Corda +is about keeping many different parties all in sync with each other. + +In a classical blockchain system all data is transmitted to everyone and if you want to do something fancy, like +a multi-party transaction, you're on your own. In Corda data is transmitted only to parties that need it and +multi-party transactions are a way of life, so we provide lots of support for managing them. + +You can learn how transactions are moved between peers and taken through the build-sign-notarise-broadcast +process in a separate tutorial, :doc:`protocol-state-machines`. + +Non-asset-oriented smart contracts +---------------------------------- + +Although this tutorial covers how to implement an owned asset, there is no requirement that states and code contracts +*must* be concerned with ownership of an asset. It is better to think of states as representing useful facts about the +world, and (code) contracts as imposing logical relations on how facts combine to produce new facts. Alternatively +you can imagine that states are like rows in a relational database and contracts are like stored procedures and +relational constraints. + +When writing a contract that handles deal-like entities rather than asset-like entities, you may wish to refer +to ":doc:`contract-irs`" and the accompanying source code. Whilst all the concepts are the same, deals are +typically not splittable or mergeable and thus you don't have to worry much about grouping of states. + +Making things happen at a particular time +----------------------------------------- + +It would be nice if you could program your node to automatically redeem your commercial paper as soon as it matures. +Corda provides a way for states to advertise scheduled events that should occur in future. Whilst this information +is by default ignored, if the corresponding *Cordapp* is installed and active in your node, and if the state is +considered relevant by your wallet (e.g. because you own it), then the node can automatically begin the process +of creating a transaction and taking it through the life cycle. You can learn more about this in the article +":doc:`event-scheduling`". + +Encumbrances +------------ + +All contract states may be *encumbered* by up to one other state, which we call an **encumbrance**. + +The encumbrance state, if present, forces additional controls over the encumbered state, since the encumbrance state contract +will also be verified during the execution of the transaction. For example, a contract state could be encumbered +with a time-lock contract state; the state is then only processable in a transaction that verifies that the time +specified in the encumbrance time-lock has passed. + +The encumbered state refers to its encumbrance by index, and the referred encumbrance state +is an output state in a particular position on the same transaction that created the encumbered state. Note that an +encumbered state that is being consumed must have its encumbrance consumed in the same transaction, otherwise the +transaction is not valid. + +The encumbrance reference is optional in the ``ContractState`` interface: + +.. container:: codeset + + .. sourcecode:: kotlin + + val encumbrance: Int? get() = null + + .. sourcecode:: java + + @Nullable + @Override + public Integer getEncumbrance() { + return null; + } + + +The time-lock contract mentioned above can be implemented very simply: + +.. container:: codeset + + .. sourcecode:: kotlin + + class TestTimeLock : Contract { + ... + override fun verify(tx: TransactionForContract) { + val time = tx.timestamp.before ?: throw IllegalStateException(...) + ... + requireThat { + "the time specified in the time-lock has passed" by + (time >= tx.inputs.filterIsInstance().single().validFrom) + } + } + ... + } + +We can then set up an encumbered state: + +.. container:: codeset + + .. sourcecode:: kotlin + + val encumberedState = Cash.State(amount = 1000.DOLLARS `issued by` defaultIssuer, owner = DUMMY_PUBKEY_1, encumbrance = 1) + val fourPmTimelock = TestTimeLock.State(Instant.parse("2015-04-17T16:00:00.00Z")) + +When we construct a transaction that generates the encumbered state, we must place the encumbrance in the corresponding output +position of that transaction. And when we subsequently consume that encumbered state, the same encumbrance state must be +available somewhere within the input set of states. + +In future, we will consider the concept of a *covenant*. This is where the encumbrance travels alongside each iteration of +the encumbered state. For example, a cash state may be encumbered with a *domicile* encumbrance, which checks the domicile of +the identity of the owner that the cash state is being moved to, in order to uphold sanction screening regulations, and prevent +cash being paid to parties domiciled in e.g. North Korea. In this case, the encumbrance should be permanently attached to +the all future cash states stemming from this one. + +We will also consider marking states that are capable of being encumbrances as such. This will prevent states being used +as encumbrances inadvertently. For example, the time-lock above would be usable as an encumbrance, but it makes no sense to +be able to encumber a cash state with another one. + +Clauses +------- + +It is typical for slightly different contracts to have lots of common logic that can be shared. For example, the +concept of being issued, being exited and being upgraded are all usually required in any contract. Corda calls these +frequently needed chunks of logic "clauses", and they can simplify development considerably. + +Clauses and how to use them are addressed in the next tutorial, ":doc:`tutorial-contract-clauses`". diff --git a/docs/build/html/_sources/tutorial-test-dsl.txt b/docs/build/html/_sources/tutorial-test-dsl.txt new file mode 100644 index 0000000000..9df0c146af --- /dev/null +++ b/docs/build/html/_sources/tutorial-test-dsl.txt @@ -0,0 +1,560 @@ +.. highlight:: kotlin +.. role:: kotlin(code) + :language: kotlin +.. raw:: html + + + + + +Writing a contract test +======================= + +This tutorial will take you through the steps required to write a contract test using Kotlin and/or Java. + +The testing DSL allows one to define a piece of the ledger with transactions referring to each other, and ways of +verifying their correctness. + +Testing single transactions +--------------------------- + +We start with the empty ledger: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun emptyLedger() { + ledger { + } + } + + .. sourcecode:: java + + import static net.corda.core.testing.JavaTestHelpers.*; + import static net.corda.core.contracts.JavaTestHelpers.*; + + @Test + public void emptyLedger() { + ledger(l -> { + return Unit.INSTANCE; // We need to return this explicitly + }); + } + +The DSL keyword ``ledger`` takes a closure that can build up several transactions and may verify their overall +correctness. A ledger is effectively a fresh world with no pre-existing transactions or services within it. + +Let's add a Cash transaction: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCashDoesntCompile() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` DUMMY_CASH_ISSUER, + owner = DUMMY_PUBKEY_1 + ) + ledger { + transaction { + input(inState) + } + } + } + + .. sourcecode:: java + + @Test + public void simpleCashDoesntCompile() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getDUMMY_CASH_ISSUER()), + getDUMMY_PUBKEY_1() + ); + ledger(l -> { + l.transaction(tx -> { + tx.input(inState); + }); + return Unit.INSTANCE; + }); + } + +We can add a transaction to the ledger using the ``transaction`` primitive. The transaction in turn may be defined by +specifying ``input``-s, ``output``-s, ``command``-s and ``attachment``-s. + +The above ``input`` call is a bit special: Transactions don't actually contain input states, just references +to output states of other transactions. Under the hood the above ``input`` call creates a dummy transaction in the +ledger (that won't be verified) which outputs the specified state, and references that from this transaction. + +The above code however doesn't compile: + +.. container:: codeset + + .. sourcecode:: kotlin + + Error:(26, 21) Kotlin: Type mismatch: inferred type is Unit but EnforceVerifyOrFail was expected + + .. sourcecode:: java + + Error:(26, 31) java: incompatible types: bad return type in lambda expression missing return value + +This is deliberate: The DSL forces us to specify either ``this.verifies()`` or ``this `fails with` "some text"`` on the +last line of ``transaction``: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCash() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = DUMMY_PUBKEY_1 + ) + ledger { + transaction { + input(inState) + this.verifies() + } + } + } + + .. sourcecode:: java + + @Test + public void simpleCash() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getDUMMY_PUBKEY_1() + ); + ledger(l -> { + l.transaction(tx -> { + tx.input(inState); + return tx.verifies(); + }); + return Unit.INSTANCE; + }); + } + +The code finally compiles. When run, it produces the following error:: + + net.corda.core.contracts.TransactionVerificationException$ContractRejection: java.lang.IllegalArgumentException: Failed requirement: for deposit [01] at issuer Snake Oil Issuer the amounts balance + +.. note:: The reference here to the 'Snake Oil Issuer' is because we are using the pre-canned ``DUMMY_CASH_ISSUER`` + identity as the issuer of our cash. + +The transaction verification failed, because the sum of inputs does not equal the sum of outputs. We can specify that +this is intended behaviour by changing ``this.verifies()`` to ``this `fails with` "the amounts balance"``: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCashFailsWith() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = DUMMY_PUBKEY_1 + ) + ledger { + transaction { + input(inState) + this `fails with` "the amounts balance" + } + } + } + + .. sourcecode:: java + + @Test + public void simpleCashFailsWith() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getDUMMY_PUBKEY_1() + ); + ledger(l -> { + l.transaction(tx -> { + tx.input(inState); + return tx.failsWith("the amounts balance"); + }); + return Unit.INSTANCE; + }); + } + +We can continue to build the transaction until it ``verifies``: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCashSuccess() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = DUMMY_PUBKEY_1 + ) + ledger { + transaction { + input(inState) + this `fails with` "the amounts balance" + output(inState.copy(owner = DUMMY_PUBKEY_2)) + command(DUMMY_PUBKEY_1) { Cash.Commands.Move() } + this.verifies() + } + } + } + + .. sourcecode:: java + + @Test + public void simpleCashSuccess() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getDUMMY_PUBKEY_1() + ); + ledger(l -> { + l.transaction(tx -> { + tx.input(inState); + tx.failsWith("the amounts balance"); + tx.output(inState.copy(inState.getAmount(), getDUMMY_PUBKEY_2())); + tx.command(getDUMMY_PUBKEY_1(), new Cash.Commands.Move()); + return tx.verifies(); + }); + return Unit.INSTANCE; + }); + } + +``output`` specifies that we want the input state to be transferred to ``DUMMY_PUBKEY_2`` and ``command`` adds the +``Move`` command itself, signed by the current owner of the input state, ``DUMMY_PUBKEY_1``. + +We constructed a complete signed cash transaction from ``DUMMY_PUBKEY_1`` to ``DUMMY_PUBKEY_2`` and verified it. Note +how we left in the ``fails with`` line - this is fine, the failure will be tested on the partially constructed +transaction. + +What should we do if we wanted to test what happens when the wrong party signs the transaction? If we simply add a +``command`` it will ruin the transaction for good... Enter ``tweak``: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCashTweakSuccess() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = DUMMY_PUBKEY_1 + ) + ledger { + transaction { + input(inState) + this `fails with` "the amounts balance" + output(inState.copy(owner = DUMMY_PUBKEY_2)) + + tweak { + command(DUMMY_PUBKEY_2) { Cash.Commands.Move() } + this `fails with` "the owning keys are the same as the signing keys" + } + + command(DUMMY_PUBKEY_1) { Cash.Commands.Move() } + this.verifies() + } + } + } + + .. sourcecode:: java + + @Test + public void simpleCashTweakSuccess() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getDUMMY_PUBKEY_1() + ); + ledger(l -> { + l.transaction(tx -> { + tx.input(inState); + tx.failsWith("the amounts balance"); + tx.output(inState.copy(inState.getAmount(), getDUMMY_PUBKEY_2())); + + tx.tweak(tw -> { + tw.command(getDUMMY_PUBKEY_2(), new Cash.Commands.Move()); + return tw.failsWith("the owning keys are the same as the signing keys"); + }); + tx.command(getDUMMY_PUBKEY_1(), new Cash.Commands.Move()); + return tx.verifies(); + }); + return Unit.INSTANCE; + }); + } + +``tweak`` creates a local copy of the transaction. This allows the local "ruining" of the transaction allowing testing +of different error conditions. + +We now have a neat little test that tests a single transaction. This is already useful, and in fact testing of a single +transaction in this way is very common. There is even a shorthand toplevel ``transaction`` primitive that creates a +ledger with a single transaction: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun simpleCashTweakSuccessTopLevelTransaction() { + val inState = Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = DUMMY_PUBKEY_1 + ) + transaction { + input(inState) + this `fails with` "the amounts balance" + output(inState.copy(owner = DUMMY_PUBKEY_2)) + + tweak { + command(DUMMY_PUBKEY_2) { Cash.Commands.Move() } + this `fails with` "the owning keys are the same as the signing keys" + } + + command(DUMMY_PUBKEY_1) { Cash.Commands.Move() } + this.verifies() + } + } + + .. sourcecode:: java + + @Test + public void simpleCashTweakSuccessTopLevelTransaction() { + Cash.State inState = new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getDUMMY_PUBKEY_1() + ); + transaction(tx -> { + tx.input(inState); + tx.failsWith("the amounts balance"); + tx.output(inState.copy(inState.getAmount(), getDUMMY_PUBKEY_2())); + + tx.tweak(tw -> { + tw.command(getDUMMY_PUBKEY_2(), new Cash.Commands.Move()); + return tw.failsWith("the owning keys are the same as the signing keys"); + }); + tx.command(getDUMMY_PUBKEY_1(), new Cash.Commands.Move()); + return tx.verifies(); + }); + } + +Chaining transactions +--------------------- + +Now that we know how to define a single transaction, let's look at how to define a chain of them: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun chainCash() { + ledger { + unverifiedTransaction { + output("MEGA_CORP cash") { + Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = MEGA_CORP_PUBKEY + ) + } + } + + transaction { + input("MEGA_CORP cash") + output("MEGA_CORP cash".output().copy(owner = DUMMY_PUBKEY_1)) + command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + this.verifies() + } + } + } + + .. sourcecode:: java + + @Test + public void chainCash() { + ledger(l -> { + l.unverifiedTransaction(tx -> { + tx.output("MEGA_CORP cash", + new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getMEGA_CORP_PUBKEY() + ) + ); + return Unit.INSTANCE; + }); + + l.transaction(tx -> { + tx.input("MEGA_CORP cash"); + Cash.State inputCash = l.retrieveOutput(Cash.State.class, "MEGA_CORP cash"); + tx.output(inputCash.copy(inputCash.getAmount(), getDUMMY_PUBKEY_1())); + tx.command(getMEGA_CORP_PUBKEY(), new Cash.Commands.Move()); + return tx.verifies(); + }); + + return Unit.INSTANCE; + }); + } + +In this example we declare that ``MEGA_CORP`` has a thousand dollars but we don't care where from, for this we can use +``unverifiedTransaction``. Note how we don't need to specify ``this.verifies()``. + +The ``output`` cash was labelled with ``"MEGA_CORP cash"``, we can subsequently referred to this other transactions, e.g. +by ``input("MEGA_CORP cash")`` or ``"MEGA_CORP cash".output()``. + +What happens if we reuse the output cash twice? + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun chainCashDoubleSpend() { + ledger { + unverifiedTransaction { + output("MEGA_CORP cash") { + Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = MEGA_CORP_PUBKEY + ) + } + } + + transaction { + input("MEGA_CORP cash") + output("MEGA_CORP cash".output().copy(owner = DUMMY_PUBKEY_1)) + command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + this.verifies() + } + + transaction { + input("MEGA_CORP cash") + // We send it to another pubkey so that the transaction is not identical to the previous one + output("MEGA_CORP cash".output().copy(owner = DUMMY_PUBKEY_2)) + command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + this.verifies() + } + } + } + + .. sourcecode:: java + + @Test + public void chainCashDoubleSpend() { + ledger(l -> { + l.unverifiedTransaction(tx -> { + tx.output("MEGA_CORP cash", + new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getMEGA_CORP_PUBKEY() + ) + ); + return Unit.INSTANCE; + }); + + l.transaction(tx -> { + tx.input("MEGA_CORP cash"); + Cash.State inputCash = l.retrieveOutput(Cash.State.class, "MEGA_CORP cash"); + tx.output(inputCash.copy(inputCash.getAmount(), getDUMMY_PUBKEY_1())); + tx.command(getMEGA_CORP_PUBKEY(), new Cash.Commands.Move()); + return tx.verifies(); + }); + + l.transaction(tx -> { + tx.input("MEGA_CORP cash"); + Cash.State inputCash = l.retrieveOutput(Cash.State.class, "MEGA_CORP cash"); + // We send it to another pubkey so that the transaction is not identical to the previous one + tx.output(inputCash.copy(inputCash.getAmount(), getDUMMY_PUBKEY_2())); + tx.command(getMEGA_CORP_PUBKEY(), new Cash.Commands.Move()); + return tx.verifies(); + }); + + return Unit.INSTANCE; + }); + } + +The transactions ``verifies()`` individually, however the state was spent twice! + +We can also verify the complete ledger by calling ``verifies``/``fails`` on the ledger level. We can also use +``tweak`` to create a local copy of the whole ledger: + +.. container:: codeset + + .. sourcecode:: kotlin + + @Test + fun chainCashDoubleSpendFailsWith() { + ledger { + unverifiedTransaction { + output("MEGA_CORP cash") { + Cash.State( + amount = 1000.DOLLARS `issued by` MEGA_CORP.ref(1, 1), + owner = MEGA_CORP_PUBKEY + ) + } + } + + transaction { + input("MEGA_CORP cash") + output("MEGA_CORP cash".output().copy(owner = DUMMY_PUBKEY_1)) + command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + this.verifies() + } + + tweak { + transaction { + input("MEGA_CORP cash") + // We send it to another pubkey so that the transaction is not identical to the previous one + output("MEGA_CORP cash".output().copy(owner = DUMMY_PUBKEY_1)) + command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + this.verifies() + } + this.fails() + } + + this.verifies() + } + } + + .. sourcecode:: java + + @Test + public void chainCashDoubleSpendFailsWith() { + ledger(l -> { + l.unverifiedTransaction(tx -> { + tx.output("MEGA_CORP cash", + new Cash.State( + issuedBy(DOLLARS(1000), getMEGA_CORP().ref((byte)1, (byte)1)), + getMEGA_CORP_PUBKEY() + ) + ); + return Unit.INSTANCE; + }); + + l.transaction(tx -> { + tx.input("MEGA_CORP cash"); + Cash.State inputCash = l.retrieveOutput(Cash.State.class, "MEGA_CORP cash"); + tx.output(inputCash.copy(inputCash.getAmount(), getDUMMY_PUBKEY_1())); + tx.command(getMEGA_CORP_PUBKEY(), new Cash.Commands.Move()); + return tx.verifies(); + }); + + l.tweak(lw -> { + lw.transaction(tx -> { + tx.input("MEGA_CORP cash"); + Cash.State inputCash = l.retrieveOutput(Cash.State.class, "MEGA_CORP cash"); + // We send it to another pubkey so that the transaction is not identical to the previous one + tx.output(inputCash.copy(inputCash.getAmount(), getDUMMY_PUBKEY_2())); + tx.command(getMEGA_CORP_PUBKEY(), new Cash.Commands.Move()); + return tx.verifies(); + }); + lw.fails(); + return Unit.INSTANCE; + }); + + l.verifies(); + return Unit.INSTANCE; + }); + } diff --git a/docs/build/html/_sources/where-to-start.txt b/docs/build/html/_sources/where-to-start.txt new file mode 100644 index 0000000000..3b8b241b6a --- /dev/null +++ b/docs/build/html/_sources/where-to-start.txt @@ -0,0 +1,69 @@ +.. highlight:: kotlin +.. raw:: html + + + + +Where to start +============== + +So you want to start experimenting with Corda. Where do you begin? Although Corda is still very early and missing +large chunks of important functionality, this article will hopefully put you on the right place. + +An experiment with Corda is started by picking a *scenario* and then turning it into a *demo*. It is important to +understand that at this stage in its life, Corda does not have a single unified server that loads everything +dynamically. Instead, Corda provides an object oriented API which is then used by a *driver* program, with one driver +per scenario. You can see the existing demo apps in action by :doc:`running-the-demos`. + +In future this design will change and there will be a single server that does everything. But for now, there isn't. + +A scenario contains: + +* A set of participating nodes and their roles. +* Some business process you wish to automate (typically simplified from the real thing). +* The smart contracts and protocols that will automate that process. + +It may also specify a REST/JSON API, but this is optional. + +Here's are two example scenarios included in the box: + +1. Bank A wishes to buy some commercial paper in return for cash. Bank B wants to issue and sell some CP to Bank A. + This is probably the simplest scenario in Corda that still does something interesting. It's like the buttered + bread of finance. +2. Bank A and Bank B want to enter into an interest rate swap and evolve it through its lifecycle. + +The process of implementing a scenario looks like this: + +1. First of all, design your states and transaction types. Read about the :doc:`data-model` if you aren't sure what that + involves. +2. Now, create a new file in the finance/src/main directory. You can either any JVM language but we only provide examples + in Java and Kotlin. The file should define your state classes and your contract class, which will define the + allowable state transitions. You can learn how these are constructed by reading the ":doc:`tutorial-contract`" tutorial. +3. It isn't enough to just define static data and logic that controls what's allowed. You must also orchestrate the + business process. This is the job of the protocol framework. You can learn how to author these by reading + ":doc:`protocol-state-machines`". +4. Once you have created your states, transactions and protocols, you need a way to demonstrate them (outside of the + unit tests, of course). This topic is covered below. + +The trader demo +--------------- + +Until Corda has a unified server that can dynamically load every aspect of an application (i.e. software implementing a scenario), +we have to do a bit of copy/paste wiring ourselves. + +The trader demo is a good place to start understanding this, which can be found in src/main/kotlin/demos/TraderDemo.kt + +The idea of a driver program is that it starts a node in one of several roles, according to a command line flag. The +driver may step through some pre-programmed scenario automatically or it may register an API to be exported via HTTP. +You would then have to drive the node externally for your demo. + +The best way to create your own scenario is not to write a driver from scratch but to copy the existing trader or IRS +demo drivers and then customise them, as much of the code would end up being shared (like for command line parsing). + +Things you will want to adjust: + +1. The name of the grouping directory each node role will create its private directory under. +2. The demo protocols that just wrap the real business process in some kind of fake trading logic. + +The IRS driver program registers REST APIs, but as this is seriously in flux right now and the APIs will change a lot, +we do not recommend you try this as part of your initial explorations unless you are feeling adventurous. \ No newline at end of file diff --git a/docs/build/html/_static/ajax-loader.gif b/docs/build/html/_static/ajax-loader.gif new file mode 100644 index 0000000000..61faf8cab2 Binary files /dev/null and b/docs/build/html/_static/ajax-loader.gif differ diff --git a/docs/build/html/_static/basic.css b/docs/build/html/_static/basic.css new file mode 100644 index 0000000000..2b513f0c96 --- /dev/null +++ b/docs/build/html/_static/basic.css @@ -0,0 +1,604 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox input[type="text"] { + width: 170px; +} + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable dl, table.indextable dd { + margin-top: 0; + margin-bottom: 0; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.field-list ul { + padding-left: 1em; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.field-list td, table.field-list th { + border: 0 !important; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, .highlighted { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/build/html/_static/codesets.js b/docs/build/html/_static/codesets.js new file mode 100644 index 0000000000..af6444d502 --- /dev/null +++ b/docs/build/html/_static/codesets.js @@ -0,0 +1,25 @@ +$(document).ready(function() { + $(".codeset").each(function(index, el) { + var c = $("
KotlinJava
"); + var kotlinButton = c.children()[0]; + var javaButton = c.children()[1]; + kotlinButton.onclick = function() { + $(el).children(".highlight-java")[0].style.display = "none"; + $(el).children(".highlight-kotlin")[0].style.display = "block"; + javaButton.setAttribute("class", ""); + kotlinButton.setAttribute("class", "current"); + }; + javaButton.onclick = function() { + $(el).children(".highlight-java")[0].style.display = "block"; + $(el).children(".highlight-kotlin")[0].style.display = "none"; + kotlinButton.setAttribute("class", ""); + javaButton.setAttribute("class", "current"); + }; + + if ($(el).children(".highlight-java").length == 0) { + // No Java for this example. + javaButton.style.display = "none"; + } + c.insertBefore(el); + }); +}); \ No newline at end of file diff --git a/docs/build/html/_static/comment-bright.png b/docs/build/html/_static/comment-bright.png new file mode 100644 index 0000000000..551517b8c8 Binary files /dev/null and b/docs/build/html/_static/comment-bright.png differ diff --git a/docs/build/html/_static/comment-close.png b/docs/build/html/_static/comment-close.png new file mode 100644 index 0000000000..09b54be46d Binary files /dev/null and b/docs/build/html/_static/comment-close.png differ diff --git a/docs/build/html/_static/comment.png b/docs/build/html/_static/comment.png new file mode 100644 index 0000000000..92feb52b88 Binary files /dev/null and b/docs/build/html/_static/comment.png differ diff --git a/docs/build/html/_static/corda-introductory-whitepaper.pdf b/docs/build/html/_static/corda-introductory-whitepaper.pdf new file mode 100644 index 0000000000..a43f57e18b Binary files /dev/null and b/docs/build/html/_static/corda-introductory-whitepaper.pdf differ diff --git a/docs/build/html/_static/corda-technical-whitepaper.pdf b/docs/build/html/_static/corda-technical-whitepaper.pdf new file mode 100644 index 0000000000..cf78900f20 Binary files /dev/null and b/docs/build/html/_static/corda-technical-whitepaper.pdf differ diff --git a/docs/build/html/_static/css/badge_only.css b/docs/build/html/_static/css/badge_only.css new file mode 100644 index 0000000000..7e17fb148c --- /dev/null +++ b/docs/build/html/_static/css/badge_only.css @@ -0,0 +1,2 @@ +.fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-weight:normal;font-style:normal;src:url("../font/fontawesome_webfont.eot");src:url("../font/fontawesome_webfont.eot?#iefix") format("embedded-opentype"),url("../font/fontawesome_webfont.woff") format("woff"),url("../font/fontawesome_webfont.ttf") format("truetype"),url("../font/fontawesome_webfont.svg#FontAwesome") format("svg")}.fa:before{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa{display:inline-block;text-decoration:inherit}li .fa{display:inline-block}li .fa-large:before,li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-0.8em}ul.fas li .fa{width:0.8em}ul.fas li .fa-large:before,ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before{content:""}.icon-book:before{content:""}.fa-caret-down:before{content:""}.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.icon-caret-up:before{content:""}.fa-caret-left:before{content:""}.icon-caret-left:before{content:""}.fa-caret-right:before{content:""}.icon-caret-right:before{content:""}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;border-top:solid 10px #343131;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}img{width:100%;height:auto}} +/*# sourceMappingURL=badge_only.css.map */ diff --git a/docs/build/html/_static/css/custom.css b/docs/build/html/_static/css/custom.css new file mode 100644 index 0000000000..2fd187f700 --- /dev/null +++ b/docs/build/html/_static/css/custom.css @@ -0,0 +1,35 @@ +@import "theme.css"; + +.highlight .k, .highlight .kd { + color: blue; +} + +.codesnippet-widgets { + min-width: 100%; + display: block; + background: lightskyblue; + color: white; + padding: 10px 0; + margin: 0 0 -1px 0; +} + +.codesnippet-widgets > span { + padding: 10px; + cursor: pointer; +} + +.codesnippet-widgets > .current { + background: deepskyblue; +} + +.codeset > .highlight-java { + display: none; +} + +.wy-nav-content { + max-width: 1000px; +} + +p { + font-size: 100%; /* Get rid of RTD rule that assumes nobody changes their browser font size */ +} \ No newline at end of file diff --git a/docs/build/html/_static/css/theme.css b/docs/build/html/_static/css/theme.css new file mode 100644 index 0000000000..7be93399a4 --- /dev/null +++ b/docs/build/html/_static/css/theme.css @@ -0,0 +1,5 @@ +*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}[hidden]{display:none}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:hover,a:active{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}blockquote{margin:0}dfn{font-style:italic}ins{background:#ff9;color:#000;text-decoration:none}mark{background:#ff0;color:#000;font-style:italic;font-weight:bold}pre,code,.rst-content tt,.rst-content code,kbd,samp{font-family:monospace,serif;_font-family:"courier new",monospace;font-size:1em}pre{white-space:pre}q{quotes:none}q:before,q:after{content:"";content:none}small{font-size:85%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}ul,ol,dl{margin:0;padding:0;list-style:none;list-style-image:none}li{list-style:none}dd{margin:0}img{border:0;-ms-interpolation-mode:bicubic;vertical-align:middle;max-width:100%}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:0;margin:0;padding:0}label{cursor:pointer}legend{border:0;*margin-left:-7px;padding:0;white-space:normal}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button;*overflow:visible}button[disabled],input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;*width:13px;*height:13px}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top;resize:vertical}table{border-collapse:collapse;border-spacing:0}td{vertical-align:top}.chromeframe{margin:0.2em 0;background:#ccc;color:#000;padding:0.2em 0}.ir{display:block;border:0;text-indent:-999em;overflow:hidden;background-color:transparent;background-repeat:no-repeat;text-align:left;direction:ltr;*line-height:0}.ir br{display:none}.hidden{display:none !important;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.relative{position:relative}big,small{font-size:100%}@media print{html,body,section{background:none !important}*{box-shadow:none !important;text-shadow:none !important;filter:none !important;-ms-filter:none !important}a,a:visited{text-decoration:underline}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,.rst-content .toctree-wrapper p.caption,h3{orphans:3;widows:3}h2,.rst-content .toctree-wrapper p.caption,h3{page-break-after:avoid}}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo,.btn,input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"],select,textarea,.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a,.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a,.wy-nav-top a{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:""}.clearfix:after{clear:both}/*! + * Font Awesome 4.2.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url("../fonts/fontawesome-webfont.eot?v=4.2.0");src:url("../fonts/fontawesome-webfont.eot?#iefix&v=4.2.0") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff?v=4.2.0") format("woff"),url("../fonts/fontawesome-webfont.ttf?v=4.2.0") format("truetype"),url("../fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular") format("svg");font-weight:normal;font-style:normal}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333em;line-height:0.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14286em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14286em;width:2.14286em;top:0.14286em;text-align:center}.fa-li.fa-lg{left:-1.85714em}.fa-border{padding:.2em .25em .15em;border:solid 0.08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left,.wy-menu-vertical li span.pull-left.toctree-expand,.wy-menu-vertical li.on a span.pull-left.toctree-expand,.wy-menu-vertical li.current>a span.pull-left.toctree-expand,.rst-content .pull-left.admonition-title,.rst-content h1 .pull-left.headerlink,.rst-content h2 .pull-left.headerlink,.rst-content h3 .pull-left.headerlink,.rst-content h4 .pull-left.headerlink,.rst-content h5 .pull-left.headerlink,.rst-content h6 .pull-left.headerlink,.rst-content dl dt .pull-left.headerlink,.rst-content p.caption .pull-left.headerlink,.rst-content tt.download span.pull-left:first-child,.rst-content code.download span.pull-left:first-child,.pull-left.icon{margin-right:.3em}.fa.pull-right,.wy-menu-vertical li span.pull-right.toctree-expand,.wy-menu-vertical li.on a span.pull-right.toctree-expand,.wy-menu-vertical li.current>a span.pull-right.toctree-expand,.rst-content .pull-right.admonition-title,.rst-content h1 .pull-right.headerlink,.rst-content h2 .pull-right.headerlink,.rst-content h3 .pull-right.headerlink,.rst-content h4 .pull-right.headerlink,.rst-content h5 .pull-right.headerlink,.rst-content h6 .pull-right.headerlink,.rst-content dl dt .pull-right.headerlink,.rst-content p.caption .pull-right.headerlink,.rst-content tt.download span.pull-right:first-child,.rst-content code.download span.pull-right:first-child,.pull-right.icon{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before,.icon-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-remove:before,.fa-close:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-gear:before,.fa-cog:before{content:""}.fa-trash-o:before{content:""}.fa-home:before,.icon-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-rotate-right:before,.fa-repeat:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before,.icon-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before{content:""}.fa-check-circle:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.rst-content .admonition-title:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before,.icon-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-warning:before,.fa-exclamation-triangle:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-gears:before,.fa-cogs:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook:before{content:""}.fa-github:before,.icon-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before,.icon-circle-arrow-left:before{content:""}.fa-arrow-circle-right:before,.icon-circle-arrow-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before,.icon-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-save:before,.fa-floppy-o:before{content:""}.fa-square:before{content:""}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before,.wy-dropdown .caret:before,.icon-caret-down:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-unsorted:before,.fa-sort:before{content:""}.fa-sort-down:before,.fa-sort-desc:before{content:""}.fa-sort-up:before,.fa-sort-asc:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-legal:before,.fa-gavel:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-flash:before,.fa-bolt:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-paste:before,.fa-clipboard:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-unlink:before,.fa-chain-broken:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:""}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:""}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:""}.fa-euro:before,.fa-eur:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-rupee:before,.fa-inr:before{content:""}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:""}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:""}.fa-won:before,.fa-krw:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before,.icon-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-turkish-lira:before,.fa-try:before{content:""}.fa-plus-square-o:before,.wy-menu-vertical li span.toctree-expand:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-institution:before,.fa-bank:before,.fa-university:before{content:""}.fa-mortar-board:before,.fa-graduation-cap:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:""}.fa-file-zip-o:before,.fa-file-archive-o:before{content:""}.fa-file-sound-o:before,.fa-file-audio-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-rebel:before{content:""}.fa-ge:before,.fa-empire:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-hacker-news:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-send:before,.fa-paper-plane:before{content:""}.fa-send-o:before,.fa-paper-plane-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:""}.fa-meanpath:before{content:""}.fa,.wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,.rst-content .admonition-title,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink,.rst-content tt.download span:first-child,.rst-content code.download span:first-child,.icon,.wy-dropdown .caret,.wy-inline-validate.wy-inline-validate-success .wy-input-context,.wy-inline-validate.wy-inline-validate-danger .wy-input-context,.wy-inline-validate.wy-inline-validate-warning .wy-input-context,.wy-inline-validate.wy-inline-validate-info .wy-input-context{font-family:inherit}.fa:before,.wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.rst-content .admonition-title:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content dl dt .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before,.icon:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before{font-family:"FontAwesome";display:inline-block;font-style:normal;font-weight:normal;line-height:1;text-decoration:inherit}a .fa,a .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand,a .rst-content .admonition-title,.rst-content a .admonition-title,a .rst-content h1 .headerlink,.rst-content h1 a .headerlink,a .rst-content h2 .headerlink,.rst-content h2 a .headerlink,a .rst-content h3 .headerlink,.rst-content h3 a .headerlink,a .rst-content h4 .headerlink,.rst-content h4 a .headerlink,a .rst-content h5 .headerlink,.rst-content h5 a .headerlink,a .rst-content h6 .headerlink,.rst-content h6 a .headerlink,a .rst-content dl dt .headerlink,.rst-content dl dt a .headerlink,a .rst-content p.caption .headerlink,.rst-content p.caption a .headerlink,a .rst-content tt.download span:first-child,.rst-content tt.download a span:first-child,a .rst-content code.download span:first-child,.rst-content code.download a span:first-child,a .icon{display:inline-block;text-decoration:inherit}.btn .fa,.btn .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .btn span.toctree-expand,.btn .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .btn span.toctree-expand,.btn .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .btn span.toctree-expand,.btn .rst-content .admonition-title,.rst-content .btn .admonition-title,.btn .rst-content h1 .headerlink,.rst-content h1 .btn .headerlink,.btn .rst-content h2 .headerlink,.rst-content h2 .btn .headerlink,.btn .rst-content h3 .headerlink,.rst-content h3 .btn .headerlink,.btn .rst-content h4 .headerlink,.rst-content h4 .btn .headerlink,.btn .rst-content h5 .headerlink,.rst-content h5 .btn .headerlink,.btn .rst-content h6 .headerlink,.rst-content h6 .btn .headerlink,.btn .rst-content dl dt .headerlink,.rst-content dl dt .btn .headerlink,.btn .rst-content p.caption .headerlink,.rst-content p.caption .btn .headerlink,.btn .rst-content tt.download span:first-child,.rst-content tt.download .btn span:first-child,.btn .rst-content code.download span:first-child,.rst-content code.download .btn span:first-child,.btn .icon,.nav .fa,.nav .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .nav span.toctree-expand,.nav .wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.on a .nav span.toctree-expand,.nav .wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.current>a .nav span.toctree-expand,.nav .rst-content .admonition-title,.rst-content .nav .admonition-title,.nav .rst-content h1 .headerlink,.rst-content h1 .nav .headerlink,.nav .rst-content h2 .headerlink,.rst-content h2 .nav .headerlink,.nav .rst-content h3 .headerlink,.rst-content h3 .nav .headerlink,.nav .rst-content h4 .headerlink,.rst-content h4 .nav .headerlink,.nav .rst-content h5 .headerlink,.rst-content h5 .nav .headerlink,.nav .rst-content h6 .headerlink,.rst-content h6 .nav .headerlink,.nav .rst-content dl dt .headerlink,.rst-content dl dt .nav .headerlink,.nav .rst-content p.caption .headerlink,.rst-content p.caption .nav .headerlink,.nav .rst-content tt.download span:first-child,.rst-content tt.download .nav span:first-child,.nav .rst-content code.download span:first-child,.rst-content code.download .nav span:first-child,.nav .icon{display:inline}.btn .fa.fa-large,.btn .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .btn span.fa-large.toctree-expand,.btn .rst-content .fa-large.admonition-title,.rst-content .btn .fa-large.admonition-title,.btn .rst-content h1 .fa-large.headerlink,.rst-content h1 .btn .fa-large.headerlink,.btn .rst-content h2 .fa-large.headerlink,.rst-content h2 .btn .fa-large.headerlink,.btn .rst-content h3 .fa-large.headerlink,.rst-content h3 .btn .fa-large.headerlink,.btn .rst-content h4 .fa-large.headerlink,.rst-content h4 .btn .fa-large.headerlink,.btn .rst-content h5 .fa-large.headerlink,.rst-content h5 .btn .fa-large.headerlink,.btn .rst-content h6 .fa-large.headerlink,.rst-content h6 .btn .fa-large.headerlink,.btn .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .btn .fa-large.headerlink,.btn .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .btn .fa-large.headerlink,.btn .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .btn span.fa-large:first-child,.btn .rst-content code.download span.fa-large:first-child,.rst-content code.download .btn span.fa-large:first-child,.btn .fa-large.icon,.nav .fa.fa-large,.nav .wy-menu-vertical li span.fa-large.toctree-expand,.wy-menu-vertical li .nav span.fa-large.toctree-expand,.nav .rst-content .fa-large.admonition-title,.rst-content .nav .fa-large.admonition-title,.nav .rst-content h1 .fa-large.headerlink,.rst-content h1 .nav .fa-large.headerlink,.nav .rst-content h2 .fa-large.headerlink,.rst-content h2 .nav .fa-large.headerlink,.nav .rst-content h3 .fa-large.headerlink,.rst-content h3 .nav .fa-large.headerlink,.nav .rst-content h4 .fa-large.headerlink,.rst-content h4 .nav .fa-large.headerlink,.nav .rst-content h5 .fa-large.headerlink,.rst-content h5 .nav .fa-large.headerlink,.nav .rst-content h6 .fa-large.headerlink,.rst-content h6 .nav .fa-large.headerlink,.nav .rst-content dl dt .fa-large.headerlink,.rst-content dl dt .nav .fa-large.headerlink,.nav .rst-content p.caption .fa-large.headerlink,.rst-content p.caption .nav .fa-large.headerlink,.nav .rst-content tt.download span.fa-large:first-child,.rst-content tt.download .nav span.fa-large:first-child,.nav .rst-content code.download span.fa-large:first-child,.rst-content code.download .nav span.fa-large:first-child,.nav .fa-large.icon{line-height:0.9em}.btn .fa.fa-spin,.btn .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .btn span.fa-spin.toctree-expand,.btn .rst-content .fa-spin.admonition-title,.rst-content .btn .fa-spin.admonition-title,.btn .rst-content h1 .fa-spin.headerlink,.rst-content h1 .btn .fa-spin.headerlink,.btn .rst-content h2 .fa-spin.headerlink,.rst-content h2 .btn .fa-spin.headerlink,.btn .rst-content h3 .fa-spin.headerlink,.rst-content h3 .btn .fa-spin.headerlink,.btn .rst-content h4 .fa-spin.headerlink,.rst-content h4 .btn .fa-spin.headerlink,.btn .rst-content h5 .fa-spin.headerlink,.rst-content h5 .btn .fa-spin.headerlink,.btn .rst-content h6 .fa-spin.headerlink,.rst-content h6 .btn .fa-spin.headerlink,.btn .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .btn .fa-spin.headerlink,.btn .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .btn .fa-spin.headerlink,.btn .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .btn span.fa-spin:first-child,.btn .rst-content code.download span.fa-spin:first-child,.rst-content code.download .btn span.fa-spin:first-child,.btn .fa-spin.icon,.nav .fa.fa-spin,.nav .wy-menu-vertical li span.fa-spin.toctree-expand,.wy-menu-vertical li .nav span.fa-spin.toctree-expand,.nav .rst-content .fa-spin.admonition-title,.rst-content .nav .fa-spin.admonition-title,.nav .rst-content h1 .fa-spin.headerlink,.rst-content h1 .nav .fa-spin.headerlink,.nav .rst-content h2 .fa-spin.headerlink,.rst-content h2 .nav .fa-spin.headerlink,.nav .rst-content h3 .fa-spin.headerlink,.rst-content h3 .nav .fa-spin.headerlink,.nav .rst-content h4 .fa-spin.headerlink,.rst-content h4 .nav .fa-spin.headerlink,.nav .rst-content h5 .fa-spin.headerlink,.rst-content h5 .nav .fa-spin.headerlink,.nav .rst-content h6 .fa-spin.headerlink,.rst-content h6 .nav .fa-spin.headerlink,.nav .rst-content dl dt .fa-spin.headerlink,.rst-content dl dt .nav .fa-spin.headerlink,.nav .rst-content p.caption .fa-spin.headerlink,.rst-content p.caption .nav .fa-spin.headerlink,.nav .rst-content tt.download span.fa-spin:first-child,.rst-content tt.download .nav span.fa-spin:first-child,.nav .rst-content code.download span.fa-spin:first-child,.rst-content code.download .nav span.fa-spin:first-child,.nav .fa-spin.icon{display:inline-block}.btn.fa:before,.wy-menu-vertical li span.btn.toctree-expand:before,.rst-content .btn.admonition-title:before,.rst-content h1 .btn.headerlink:before,.rst-content h2 .btn.headerlink:before,.rst-content h3 .btn.headerlink:before,.rst-content h4 .btn.headerlink:before,.rst-content h5 .btn.headerlink:before,.rst-content h6 .btn.headerlink:before,.rst-content dl dt .btn.headerlink:before,.rst-content p.caption .btn.headerlink:before,.rst-content tt.download span.btn:first-child:before,.rst-content code.download span.btn:first-child:before,.btn.icon:before{opacity:0.5;-webkit-transition:opacity 0.05s ease-in;-moz-transition:opacity 0.05s ease-in;transition:opacity 0.05s ease-in}.btn.fa:hover:before,.wy-menu-vertical li span.btn.toctree-expand:hover:before,.rst-content .btn.admonition-title:hover:before,.rst-content h1 .btn.headerlink:hover:before,.rst-content h2 .btn.headerlink:hover:before,.rst-content h3 .btn.headerlink:hover:before,.rst-content h4 .btn.headerlink:hover:before,.rst-content h5 .btn.headerlink:hover:before,.rst-content h6 .btn.headerlink:hover:before,.rst-content dl dt .btn.headerlink:hover:before,.rst-content p.caption .btn.headerlink:hover:before,.rst-content tt.download span.btn:first-child:hover:before,.rst-content code.download span.btn:first-child:hover:before,.btn.icon:hover:before{opacity:1}.btn-mini .fa:before,.btn-mini .wy-menu-vertical li span.toctree-expand:before,.wy-menu-vertical li .btn-mini span.toctree-expand:before,.btn-mini .rst-content .admonition-title:before,.rst-content .btn-mini .admonition-title:before,.btn-mini .rst-content h1 .headerlink:before,.rst-content h1 .btn-mini .headerlink:before,.btn-mini .rst-content h2 .headerlink:before,.rst-content h2 .btn-mini .headerlink:before,.btn-mini .rst-content h3 .headerlink:before,.rst-content h3 .btn-mini .headerlink:before,.btn-mini .rst-content h4 .headerlink:before,.rst-content h4 .btn-mini .headerlink:before,.btn-mini .rst-content h5 .headerlink:before,.rst-content h5 .btn-mini .headerlink:before,.btn-mini .rst-content h6 .headerlink:before,.rst-content h6 .btn-mini .headerlink:before,.btn-mini .rst-content dl dt .headerlink:before,.rst-content dl dt .btn-mini .headerlink:before,.btn-mini .rst-content p.caption .headerlink:before,.rst-content p.caption .btn-mini .headerlink:before,.btn-mini .rst-content tt.download span:first-child:before,.rst-content tt.download .btn-mini span:first-child:before,.btn-mini .rst-content code.download span:first-child:before,.rst-content code.download .btn-mini span:first-child:before,.btn-mini .icon:before{font-size:14px;vertical-align:-15%}.wy-alert,.rst-content .note,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .warning,.rst-content .seealso,.rst-content .admonition-todo{padding:12px;line-height:24px;margin-bottom:24px;background:#e7f2fa}.wy-alert-title,.rst-content .admonition-title{color:#fff;font-weight:bold;display:block;color:#fff;background:#6ab0de;margin:-12px;padding:6px 12px;margin-bottom:12px}.wy-alert.wy-alert-danger,.rst-content .wy-alert-danger.note,.rst-content .wy-alert-danger.attention,.rst-content .wy-alert-danger.caution,.rst-content .danger,.rst-content .error,.rst-content .wy-alert-danger.hint,.rst-content .wy-alert-danger.important,.rst-content .wy-alert-danger.tip,.rst-content .wy-alert-danger.warning,.rst-content .wy-alert-danger.seealso,.rst-content .wy-alert-danger.admonition-todo{background:#fdf3f2}.wy-alert.wy-alert-danger .wy-alert-title,.rst-content .wy-alert-danger.note .wy-alert-title,.rst-content .wy-alert-danger.attention .wy-alert-title,.rst-content .wy-alert-danger.caution .wy-alert-title,.rst-content .danger .wy-alert-title,.rst-content .error .wy-alert-title,.rst-content .wy-alert-danger.hint .wy-alert-title,.rst-content .wy-alert-danger.important .wy-alert-title,.rst-content .wy-alert-danger.tip .wy-alert-title,.rst-content .wy-alert-danger.warning .wy-alert-title,.rst-content .wy-alert-danger.seealso .wy-alert-title,.rst-content .wy-alert-danger.admonition-todo .wy-alert-title,.wy-alert.wy-alert-danger .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-danger .admonition-title,.rst-content .wy-alert-danger.note .admonition-title,.rst-content .wy-alert-danger.attention .admonition-title,.rst-content .wy-alert-danger.caution .admonition-title,.rst-content .danger .admonition-title,.rst-content .error .admonition-title,.rst-content .wy-alert-danger.hint .admonition-title,.rst-content .wy-alert-danger.important .admonition-title,.rst-content .wy-alert-danger.tip .admonition-title,.rst-content .wy-alert-danger.warning .admonition-title,.rst-content .wy-alert-danger.seealso .admonition-title,.rst-content .wy-alert-danger.admonition-todo .admonition-title{background:#f29f97}.wy-alert.wy-alert-warning,.rst-content .wy-alert-warning.note,.rst-content .attention,.rst-content .caution,.rst-content .wy-alert-warning.danger,.rst-content .wy-alert-warning.error,.rst-content .wy-alert-warning.hint,.rst-content .wy-alert-warning.important,.rst-content .wy-alert-warning.tip,.rst-content .warning,.rst-content .wy-alert-warning.seealso,.rst-content .admonition-todo{background:#ffedcc}.wy-alert.wy-alert-warning .wy-alert-title,.rst-content .wy-alert-warning.note .wy-alert-title,.rst-content .attention .wy-alert-title,.rst-content .caution .wy-alert-title,.rst-content .wy-alert-warning.danger .wy-alert-title,.rst-content .wy-alert-warning.error .wy-alert-title,.rst-content .wy-alert-warning.hint .wy-alert-title,.rst-content .wy-alert-warning.important .wy-alert-title,.rst-content .wy-alert-warning.tip .wy-alert-title,.rst-content .warning .wy-alert-title,.rst-content .wy-alert-warning.seealso .wy-alert-title,.rst-content .admonition-todo .wy-alert-title,.wy-alert.wy-alert-warning .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-warning .admonition-title,.rst-content .wy-alert-warning.note .admonition-title,.rst-content .attention .admonition-title,.rst-content .caution .admonition-title,.rst-content .wy-alert-warning.danger .admonition-title,.rst-content .wy-alert-warning.error .admonition-title,.rst-content .wy-alert-warning.hint .admonition-title,.rst-content .wy-alert-warning.important .admonition-title,.rst-content .wy-alert-warning.tip .admonition-title,.rst-content .warning .admonition-title,.rst-content .wy-alert-warning.seealso .admonition-title,.rst-content .admonition-todo .admonition-title{background:#f0b37e}.wy-alert.wy-alert-info,.rst-content .note,.rst-content .wy-alert-info.attention,.rst-content .wy-alert-info.caution,.rst-content .wy-alert-info.danger,.rst-content .wy-alert-info.error,.rst-content .wy-alert-info.hint,.rst-content .wy-alert-info.important,.rst-content .wy-alert-info.tip,.rst-content .wy-alert-info.warning,.rst-content .seealso,.rst-content .wy-alert-info.admonition-todo{background:#e7f2fa}.wy-alert.wy-alert-info .wy-alert-title,.rst-content .note .wy-alert-title,.rst-content .wy-alert-info.attention .wy-alert-title,.rst-content .wy-alert-info.caution .wy-alert-title,.rst-content .wy-alert-info.danger .wy-alert-title,.rst-content .wy-alert-info.error .wy-alert-title,.rst-content .wy-alert-info.hint .wy-alert-title,.rst-content .wy-alert-info.important .wy-alert-title,.rst-content .wy-alert-info.tip .wy-alert-title,.rst-content .wy-alert-info.warning .wy-alert-title,.rst-content .seealso .wy-alert-title,.rst-content .wy-alert-info.admonition-todo .wy-alert-title,.wy-alert.wy-alert-info .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-info .admonition-title,.rst-content .note .admonition-title,.rst-content .wy-alert-info.attention .admonition-title,.rst-content .wy-alert-info.caution .admonition-title,.rst-content .wy-alert-info.danger .admonition-title,.rst-content .wy-alert-info.error .admonition-title,.rst-content .wy-alert-info.hint .admonition-title,.rst-content .wy-alert-info.important .admonition-title,.rst-content .wy-alert-info.tip .admonition-title,.rst-content .wy-alert-info.warning .admonition-title,.rst-content .seealso .admonition-title,.rst-content .wy-alert-info.admonition-todo .admonition-title{background:#6ab0de}.wy-alert.wy-alert-success,.rst-content .wy-alert-success.note,.rst-content .wy-alert-success.attention,.rst-content .wy-alert-success.caution,.rst-content .wy-alert-success.danger,.rst-content .wy-alert-success.error,.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .wy-alert-success.warning,.rst-content .wy-alert-success.seealso,.rst-content .wy-alert-success.admonition-todo{background:#dbfaf4}.wy-alert.wy-alert-success .wy-alert-title,.rst-content .wy-alert-success.note .wy-alert-title,.rst-content .wy-alert-success.attention .wy-alert-title,.rst-content .wy-alert-success.caution .wy-alert-title,.rst-content .wy-alert-success.danger .wy-alert-title,.rst-content .wy-alert-success.error .wy-alert-title,.rst-content .hint .wy-alert-title,.rst-content .important .wy-alert-title,.rst-content .tip .wy-alert-title,.rst-content .wy-alert-success.warning .wy-alert-title,.rst-content .wy-alert-success.seealso .wy-alert-title,.rst-content .wy-alert-success.admonition-todo .wy-alert-title,.wy-alert.wy-alert-success .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-success .admonition-title,.rst-content .wy-alert-success.note .admonition-title,.rst-content .wy-alert-success.attention .admonition-title,.rst-content .wy-alert-success.caution .admonition-title,.rst-content .wy-alert-success.danger .admonition-title,.rst-content .wy-alert-success.error .admonition-title,.rst-content .hint .admonition-title,.rst-content .important .admonition-title,.rst-content .tip .admonition-title,.rst-content .wy-alert-success.warning .admonition-title,.rst-content .wy-alert-success.seealso .admonition-title,.rst-content .wy-alert-success.admonition-todo .admonition-title{background:#1abc9c}.wy-alert.wy-alert-neutral,.rst-content .wy-alert-neutral.note,.rst-content .wy-alert-neutral.attention,.rst-content .wy-alert-neutral.caution,.rst-content .wy-alert-neutral.danger,.rst-content .wy-alert-neutral.error,.rst-content .wy-alert-neutral.hint,.rst-content .wy-alert-neutral.important,.rst-content .wy-alert-neutral.tip,.rst-content .wy-alert-neutral.warning,.rst-content .wy-alert-neutral.seealso,.rst-content .wy-alert-neutral.admonition-todo{background:#f3f6f6}.wy-alert.wy-alert-neutral .wy-alert-title,.rst-content .wy-alert-neutral.note .wy-alert-title,.rst-content .wy-alert-neutral.attention .wy-alert-title,.rst-content .wy-alert-neutral.caution .wy-alert-title,.rst-content .wy-alert-neutral.danger .wy-alert-title,.rst-content .wy-alert-neutral.error .wy-alert-title,.rst-content .wy-alert-neutral.hint .wy-alert-title,.rst-content .wy-alert-neutral.important .wy-alert-title,.rst-content .wy-alert-neutral.tip .wy-alert-title,.rst-content .wy-alert-neutral.warning .wy-alert-title,.rst-content .wy-alert-neutral.seealso .wy-alert-title,.rst-content .wy-alert-neutral.admonition-todo .wy-alert-title,.wy-alert.wy-alert-neutral .rst-content .admonition-title,.rst-content .wy-alert.wy-alert-neutral .admonition-title,.rst-content .wy-alert-neutral.note .admonition-title,.rst-content .wy-alert-neutral.attention .admonition-title,.rst-content .wy-alert-neutral.caution .admonition-title,.rst-content .wy-alert-neutral.danger .admonition-title,.rst-content .wy-alert-neutral.error .admonition-title,.rst-content .wy-alert-neutral.hint .admonition-title,.rst-content .wy-alert-neutral.important .admonition-title,.rst-content .wy-alert-neutral.tip .admonition-title,.rst-content .wy-alert-neutral.warning .admonition-title,.rst-content .wy-alert-neutral.seealso .admonition-title,.rst-content .wy-alert-neutral.admonition-todo .admonition-title{color:#404040;background:#e1e4e5}.wy-alert.wy-alert-neutral a,.rst-content .wy-alert-neutral.note a,.rst-content .wy-alert-neutral.attention a,.rst-content .wy-alert-neutral.caution a,.rst-content .wy-alert-neutral.danger a,.rst-content .wy-alert-neutral.error a,.rst-content .wy-alert-neutral.hint a,.rst-content .wy-alert-neutral.important a,.rst-content .wy-alert-neutral.tip a,.rst-content .wy-alert-neutral.warning a,.rst-content .wy-alert-neutral.seealso a,.rst-content .wy-alert-neutral.admonition-todo a{color:#2980B9}.wy-alert p:last-child,.rst-content .note p:last-child,.rst-content .attention p:last-child,.rst-content .caution p:last-child,.rst-content .danger p:last-child,.rst-content .error p:last-child,.rst-content .hint p:last-child,.rst-content .important p:last-child,.rst-content .tip p:last-child,.rst-content .warning p:last-child,.rst-content .seealso p:last-child,.rst-content .admonition-todo p:last-child{margin-bottom:0}.wy-tray-container{position:fixed;bottom:0px;left:0;z-index:600}.wy-tray-container li{display:block;width:300px;background:transparent;color:#fff;text-align:center;box-shadow:0 5px 5px 0 rgba(0,0,0,0.1);padding:0 24px;min-width:20%;opacity:0;height:0;line-height:56px;overflow:hidden;-webkit-transition:all 0.3s ease-in;-moz-transition:all 0.3s ease-in;transition:all 0.3s ease-in}.wy-tray-container li.wy-tray-item-success{background:#27AE60}.wy-tray-container li.wy-tray-item-info{background:#2980B9}.wy-tray-container li.wy-tray-item-warning{background:#E67E22}.wy-tray-container li.wy-tray-item-danger{background:#E74C3C}.wy-tray-container li.on{opacity:1;height:56px}@media screen and (max-width: 768px){.wy-tray-container{bottom:auto;top:0;width:100%}.wy-tray-container li{width:100%}}button{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle;cursor:pointer;line-height:normal;-webkit-appearance:button;*overflow:visible}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}button[disabled]{cursor:default}.btn{display:inline-block;border-radius:2px;line-height:normal;white-space:nowrap;text-align:center;cursor:pointer;font-size:100%;padding:6px 12px 8px 12px;color:#fff;border:1px solid rgba(0,0,0,0.1);background-color:#27AE60;text-decoration:none;font-weight:normal;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:0px 1px 2px -1px rgba(255,255,255,0.5) inset,0px -2px 0px 0px rgba(0,0,0,0.1) inset;outline-none:false;vertical-align:middle;*display:inline;zoom:1;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-transition:all 0.1s linear;-moz-transition:all 0.1s linear;transition:all 0.1s linear}.btn-hover{background:#2e8ece;color:#fff}.btn:hover{background:#2cc36b;color:#fff}.btn:focus{background:#2cc36b;outline:0}.btn:active{box-shadow:0px -1px 0px 0px rgba(0,0,0,0.05) inset,0px 2px 0px 0px rgba(0,0,0,0.1) inset;padding:8px 12px 6px 12px}.btn:visited{color:#fff}.btn:disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:0.4;cursor:not-allowed;box-shadow:none}.btn-disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:0.4;cursor:not-allowed;box-shadow:none}.btn-disabled:hover,.btn-disabled:focus,.btn-disabled:active{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:0.4;cursor:not-allowed;box-shadow:none}.btn::-moz-focus-inner{padding:0;border:0}.btn-small{font-size:80%}.btn-info{background-color:#2980B9 !important}.btn-info:hover{background-color:#2e8ece !important}.btn-neutral{background-color:#f3f6f6 !important;color:#404040 !important}.btn-neutral:hover{background-color:#e5ebeb !important;color:#404040}.btn-neutral:visited{color:#404040 !important}.btn-success{background-color:#27AE60 !important}.btn-success:hover{background-color:#295 !important}.btn-danger{background-color:#E74C3C !important}.btn-danger:hover{background-color:#ea6153 !important}.btn-warning{background-color:#E67E22 !important}.btn-warning:hover{background-color:#e98b39 !important}.btn-invert{background-color:#222}.btn-invert:hover{background-color:#2f2f2f !important}.btn-link{background-color:transparent !important;color:#2980B9;box-shadow:none;border-color:transparent !important}.btn-link:hover{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:active{background-color:transparent !important;color:#409ad5 !important;box-shadow:none}.btn-link:visited{color:#9B59B6}.wy-btn-group .btn,.wy-control .btn{vertical-align:middle}.wy-btn-group{margin-bottom:24px;*zoom:1}.wy-btn-group:before,.wy-btn-group:after{display:table;content:""}.wy-btn-group:after{clear:both}.wy-dropdown{position:relative;display:inline-block}.wy-dropdown-active .wy-dropdown-menu{display:block}.wy-dropdown-menu{position:absolute;left:0;display:none;float:left;top:100%;min-width:100%;background:#fcfcfc;z-index:100;border:solid 1px #cfd7dd;box-shadow:0 2px 2px 0 rgba(0,0,0,0.1);padding:12px}.wy-dropdown-menu>dd>a{display:block;clear:both;color:#404040;white-space:nowrap;font-size:90%;padding:0 12px;cursor:pointer}.wy-dropdown-menu>dd>a:hover{background:#2980B9;color:#fff}.wy-dropdown-menu>dd.divider{border-top:solid 1px #cfd7dd;margin:6px 0}.wy-dropdown-menu>dd.search{padding-bottom:12px}.wy-dropdown-menu>dd.search input[type="search"]{width:100%}.wy-dropdown-menu>dd.call-to-action{background:#e3e3e3;text-transform:uppercase;font-weight:500;font-size:80%}.wy-dropdown-menu>dd.call-to-action:hover{background:#e3e3e3}.wy-dropdown-menu>dd.call-to-action .btn{color:#fff}.wy-dropdown.wy-dropdown-up .wy-dropdown-menu{bottom:100%;top:auto;left:auto;right:0}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu{background:#fcfcfc;margin-top:2px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a{padding:6px 12px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a:hover{background:#2980B9;color:#fff}.wy-dropdown.wy-dropdown-left .wy-dropdown-menu{right:0;left:auto;text-align:right}.wy-dropdown-arrow:before{content:" ";border-bottom:5px solid #f5f5f5;border-left:5px solid transparent;border-right:5px solid transparent;position:absolute;display:block;top:-4px;left:50%;margin-left:-3px}.wy-dropdown-arrow.wy-dropdown-arrow-left:before{left:11px}.wy-form-stacked select{display:block}.wy-form-aligned input,.wy-form-aligned textarea,.wy-form-aligned select,.wy-form-aligned .wy-help-inline,.wy-form-aligned label{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-form-aligned .wy-control-group>label{display:inline-block;vertical-align:middle;width:10em;margin:6px 12px 0 0;float:left}.wy-form-aligned .wy-control{float:left}.wy-form-aligned .wy-control label{display:block}.wy-form-aligned .wy-control select{margin-top:6px}fieldset{border:0;margin:0;padding:0}legend{display:block;width:100%;border:0;padding:0;white-space:normal;margin-bottom:24px;font-size:150%;*margin-left:-7px}label{display:block;margin:0 0 0.3125em 0;color:#333;font-size:90%}input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.wy-control-group{margin-bottom:24px;*zoom:1;max-width:68em;margin-left:auto;margin-right:auto;*zoom:1}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group:before,.wy-control-group:after{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group.wy-control-group-required>label:after{content:" *";color:#E74C3C}.wy-control-group .wy-form-full,.wy-control-group .wy-form-halves,.wy-control-group .wy-form-thirds{padding-bottom:12px}.wy-control-group .wy-form-full select,.wy-control-group .wy-form-halves select,.wy-control-group .wy-form-thirds select{width:100%}.wy-control-group .wy-form-full input[type="text"],.wy-control-group .wy-form-full input[type="password"],.wy-control-group .wy-form-full input[type="email"],.wy-control-group .wy-form-full input[type="url"],.wy-control-group .wy-form-full input[type="date"],.wy-control-group .wy-form-full input[type="month"],.wy-control-group .wy-form-full input[type="time"],.wy-control-group .wy-form-full input[type="datetime"],.wy-control-group .wy-form-full input[type="datetime-local"],.wy-control-group .wy-form-full input[type="week"],.wy-control-group .wy-form-full input[type="number"],.wy-control-group .wy-form-full input[type="search"],.wy-control-group .wy-form-full input[type="tel"],.wy-control-group .wy-form-full input[type="color"],.wy-control-group .wy-form-halves input[type="text"],.wy-control-group .wy-form-halves input[type="password"],.wy-control-group .wy-form-halves input[type="email"],.wy-control-group .wy-form-halves input[type="url"],.wy-control-group .wy-form-halves input[type="date"],.wy-control-group .wy-form-halves input[type="month"],.wy-control-group .wy-form-halves input[type="time"],.wy-control-group .wy-form-halves input[type="datetime"],.wy-control-group .wy-form-halves input[type="datetime-local"],.wy-control-group .wy-form-halves input[type="week"],.wy-control-group .wy-form-halves input[type="number"],.wy-control-group .wy-form-halves input[type="search"],.wy-control-group .wy-form-halves input[type="tel"],.wy-control-group .wy-form-halves input[type="color"],.wy-control-group .wy-form-thirds input[type="text"],.wy-control-group .wy-form-thirds input[type="password"],.wy-control-group .wy-form-thirds input[type="email"],.wy-control-group .wy-form-thirds input[type="url"],.wy-control-group .wy-form-thirds input[type="date"],.wy-control-group .wy-form-thirds input[type="month"],.wy-control-group .wy-form-thirds input[type="time"],.wy-control-group .wy-form-thirds input[type="datetime"],.wy-control-group .wy-form-thirds input[type="datetime-local"],.wy-control-group .wy-form-thirds input[type="week"],.wy-control-group .wy-form-thirds input[type="number"],.wy-control-group .wy-form-thirds input[type="search"],.wy-control-group .wy-form-thirds input[type="tel"],.wy-control-group .wy-form-thirds input[type="color"]{width:100%}.wy-control-group .wy-form-full{float:left;display:block;margin-right:2.35765%;width:100%;margin-right:0}.wy-control-group .wy-form-full:last-child{margin-right:0}.wy-control-group .wy-form-halves{float:left;display:block;margin-right:2.35765%;width:48.82117%}.wy-control-group .wy-form-halves:last-child{margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n){margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(2n+1){clear:left}.wy-control-group .wy-form-thirds{float:left;display:block;margin-right:2.35765%;width:31.76157%}.wy-control-group .wy-form-thirds:last-child{margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n){margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n+1){clear:left}.wy-control-group.wy-control-group-no-input .wy-control{margin:6px 0 0 0;font-size:90%}.wy-control-no-input{display:inline-block;margin:6px 0 0 0;font-size:90%}.wy-control-group.fluid-input input[type="text"],.wy-control-group.fluid-input input[type="password"],.wy-control-group.fluid-input input[type="email"],.wy-control-group.fluid-input input[type="url"],.wy-control-group.fluid-input input[type="date"],.wy-control-group.fluid-input input[type="month"],.wy-control-group.fluid-input input[type="time"],.wy-control-group.fluid-input input[type="datetime"],.wy-control-group.fluid-input input[type="datetime-local"],.wy-control-group.fluid-input input[type="week"],.wy-control-group.fluid-input input[type="number"],.wy-control-group.fluid-input input[type="search"],.wy-control-group.fluid-input input[type="tel"],.wy-control-group.fluid-input input[type="color"]{width:100%}.wy-form-message-inline{display:inline-block;padding-left:0.3em;color:#666;vertical-align:middle;font-size:90%}.wy-form-message{display:block;color:#999;font-size:70%;margin-top:0.3125em;font-style:italic}.wy-form-message p{font-size:inherit;font-style:italic;margin-bottom:6px}.wy-form-message p:last-child{margin-bottom:0}input{line-height:normal}input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;*overflow:visible}input[type="text"],input[type="password"],input[type="email"],input[type="url"],input[type="date"],input[type="month"],input[type="time"],input[type="datetime"],input[type="datetime-local"],input[type="week"],input[type="number"],input[type="search"],input[type="tel"],input[type="color"]{-webkit-appearance:none;padding:6px;display:inline-block;border:1px solid #ccc;font-size:80%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;box-shadow:inset 0 1px 3px #ddd;border-radius:0;-webkit-transition:border 0.3s linear;-moz-transition:border 0.3s linear;transition:border 0.3s linear}input[type="datetime-local"]{padding:0.34375em 0.625em}input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0;margin-right:0.3125em;*height:13px;*width:13px}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}input[type="text"]:focus,input[type="password"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus{outline:0;outline:thin dotted \9;border-color:#333}input.no-focus:focus{border-color:#ccc !important}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:1px auto #129FEA}input[type="text"][disabled],input[type="password"][disabled],input[type="email"][disabled],input[type="url"][disabled],input[type="date"][disabled],input[type="month"][disabled],input[type="time"][disabled],input[type="datetime"][disabled],input[type="datetime-local"][disabled],input[type="week"][disabled],input[type="number"][disabled],input[type="search"][disabled],input[type="tel"][disabled],input[type="color"][disabled]{cursor:not-allowed;background-color:#fafafa}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#E74C3C;border:1px solid #E74C3C}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#E74C3C}input[type="file"]:focus:invalid:focus,input[type="radio"]:focus:invalid:focus,input[type="checkbox"]:focus:invalid:focus{outline-color:#E74C3C}input.wy-input-large{padding:12px;font-size:100%}textarea{overflow:auto;vertical-align:top;width:100%;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif}select,textarea{padding:0.5em 0.625em;display:inline-block;border:1px solid #ccc;font-size:80%;box-shadow:inset 0 1px 3px #ddd;-webkit-transition:border 0.3s linear;-moz-transition:border 0.3s linear;transition:border 0.3s linear}select{border:1px solid #ccc;background-color:#fff}select[multiple]{height:auto}select:focus,textarea:focus{outline:0}select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#fafafa}input[type="radio"][disabled],input[type="checkbox"][disabled]{cursor:not-allowed}.wy-checkbox,.wy-radio{margin:6px 0;color:#404040;display:block}.wy-checkbox input,.wy-radio input{vertical-align:baseline}.wy-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-input-prefix,.wy-input-suffix{white-space:nowrap;padding:6px}.wy-input-prefix .wy-input-context,.wy-input-suffix .wy-input-context{line-height:27px;padding:0 8px;display:inline-block;font-size:80%;background-color:#f3f6f6;border:solid 1px #ccc;color:#999}.wy-input-suffix .wy-input-context{border-left:0}.wy-input-prefix .wy-input-context{border-right:0}.wy-switch{width:36px;height:12px;margin:12px 0;position:relative;border-radius:4px;background:#ccc;cursor:pointer;-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out}.wy-switch:before{position:absolute;content:"";display:block;width:18px;height:18px;border-radius:4px;background:#999;left:-3px;top:-3px;-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out}.wy-switch:after{content:"false";position:absolute;left:48px;display:block;font-size:12px;color:#ccc}.wy-switch.active{background:#1e8449}.wy-switch.active:before{left:24px;background:#27AE60}.wy-switch.active:after{content:"true"}.wy-switch.disabled,.wy-switch.active.disabled{cursor:not-allowed}.wy-control-group.wy-control-group-error .wy-form-message,.wy-control-group.wy-control-group-error>label{color:#E74C3C}.wy-control-group.wy-control-group-error input[type="text"],.wy-control-group.wy-control-group-error input[type="password"],.wy-control-group.wy-control-group-error input[type="email"],.wy-control-group.wy-control-group-error input[type="url"],.wy-control-group.wy-control-group-error input[type="date"],.wy-control-group.wy-control-group-error input[type="month"],.wy-control-group.wy-control-group-error input[type="time"],.wy-control-group.wy-control-group-error input[type="datetime"],.wy-control-group.wy-control-group-error input[type="datetime-local"],.wy-control-group.wy-control-group-error input[type="week"],.wy-control-group.wy-control-group-error input[type="number"],.wy-control-group.wy-control-group-error input[type="search"],.wy-control-group.wy-control-group-error input[type="tel"],.wy-control-group.wy-control-group-error input[type="color"]{border:solid 1px #E74C3C}.wy-control-group.wy-control-group-error textarea{border:solid 1px #E74C3C}.wy-inline-validate{white-space:nowrap}.wy-inline-validate .wy-input-context{padding:0.5em 0.625em;display:inline-block;font-size:80%}.wy-inline-validate.wy-inline-validate-success .wy-input-context{color:#27AE60}.wy-inline-validate.wy-inline-validate-danger .wy-input-context{color:#E74C3C}.wy-inline-validate.wy-inline-validate-warning .wy-input-context{color:#E67E22}.wy-inline-validate.wy-inline-validate-info .wy-input-context{color:#2980B9}.rotate-90{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.rotate-180{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.rotate-270{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.mirror{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1)}.mirror.rotate-90{-webkit-transform:scaleX(-1) rotate(90deg);-moz-transform:scaleX(-1) rotate(90deg);-ms-transform:scaleX(-1) rotate(90deg);-o-transform:scaleX(-1) rotate(90deg);transform:scaleX(-1) rotate(90deg)}.mirror.rotate-180{-webkit-transform:scaleX(-1) rotate(180deg);-moz-transform:scaleX(-1) rotate(180deg);-ms-transform:scaleX(-1) rotate(180deg);-o-transform:scaleX(-1) rotate(180deg);transform:scaleX(-1) rotate(180deg)}.mirror.rotate-270{-webkit-transform:scaleX(-1) rotate(270deg);-moz-transform:scaleX(-1) rotate(270deg);-ms-transform:scaleX(-1) rotate(270deg);-o-transform:scaleX(-1) rotate(270deg);transform:scaleX(-1) rotate(270deg)}@media only screen and (max-width: 480px){.wy-form button[type="submit"]{margin:0.7em 0 0}.wy-form input[type="text"],.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:0.3em;display:block}.wy-form label{margin-bottom:0.3em;display:block}.wy-form input[type="password"],.wy-form input[type="email"],.wy-form input[type="url"],.wy-form input[type="date"],.wy-form input[type="month"],.wy-form input[type="time"],.wy-form input[type="datetime"],.wy-form input[type="datetime-local"],.wy-form input[type="week"],.wy-form input[type="number"],.wy-form input[type="search"],.wy-form input[type="tel"],.wy-form input[type="color"]{margin-bottom:0}.wy-form-aligned .wy-control-group label{margin-bottom:0.3em;text-align:left;display:block;width:100%}.wy-form-aligned .wy-control{margin:1.5em 0 0 0}.wy-form .wy-help-inline,.wy-form-message-inline,.wy-form-message{display:block;font-size:80%;padding:6px 0}}@media screen and (max-width: 768px){.tablet-hide{display:none}}@media screen and (max-width: 480px){.mobile-hide{display:none}}.float-left{float:left}.float-right{float:right}.full-width{width:100%}.wy-table,.rst-content table.docutils,.rst-content table.field-list{border-collapse:collapse;border-spacing:0;empty-cells:show;margin-bottom:24px}.wy-table caption,.rst-content table.docutils caption,.rst-content table.field-list caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td,.wy-table th,.rst-content table.docutils th,.rst-content table.field-list th{font-size:90%;margin:0;overflow:visible;padding:8px 16px}.wy-table td:first-child,.rst-content table.docutils td:first-child,.rst-content table.field-list td:first-child,.wy-table th:first-child,.rst-content table.docutils th:first-child,.rst-content table.field-list th:first-child{border-left-width:0}.wy-table thead,.rst-content table.docutils thead,.rst-content table.field-list thead{color:#000;text-align:left;vertical-align:bottom;white-space:nowrap}.wy-table thead th,.rst-content table.docutils thead th,.rst-content table.field-list thead th{font-weight:bold;border-bottom:solid 2px #e1e4e5}.wy-table td,.rst-content table.docutils td,.rst-content table.field-list td{background-color:transparent;vertical-align:middle}.wy-table td p,.rst-content table.docutils td p,.rst-content table.field-list td p{line-height:18px}.wy-table td p:last-child,.rst-content table.docutils td p:last-child,.rst-content table.field-list td p:last-child{margin-bottom:0}.wy-table .wy-table-cell-min,.rst-content table.docutils .wy-table-cell-min,.rst-content table.field-list .wy-table-cell-min{width:1%;padding-right:0}.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox],.wy-table .wy-table-cell-min input[type=checkbox],.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox]{margin:0}.wy-table-secondary{color:gray;font-size:90%}.wy-table-tertiary{color:gray;font-size:80%}.wy-table-odd td,.wy-table-striped tr:nth-child(2n-1) td,.rst-content table.docutils:not(.field-list) tr:nth-child(2n-1) td{background-color:#f3f6f6}.wy-table-backed{background-color:#f3f6f6}.wy-table-bordered-all,.rst-content table.docutils{border:1px solid #e1e4e5}.wy-table-bordered-all td,.rst-content table.docutils td{border-bottom:1px solid #e1e4e5;border-left:1px solid #e1e4e5}.wy-table-bordered-all tbody>tr:last-child td,.rst-content table.docutils tbody>tr:last-child td{border-bottom-width:0}.wy-table-bordered{border:1px solid #e1e4e5}.wy-table-bordered-rows td{border-bottom:1px solid #e1e4e5}.wy-table-bordered-rows tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal td,.wy-table-horizontal th{border-width:0 0 1px 0;border-bottom:1px solid #e1e4e5}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-responsive{margin-bottom:24px;max-width:100%;overflow:auto}.wy-table-responsive table{margin-bottom:0 !important}.wy-table-responsive table td,.wy-table-responsive table th{white-space:nowrap}a{color:#2980B9;text-decoration:none;cursor:pointer}a:hover{color:#3091d1}a:visited{color:#9B59B6}html{height:100%;overflow-x:hidden}body{font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;font-weight:normal;color:#404040;min-height:100%;overflow-x:hidden;background:#edf0f2}.wy-text-left{text-align:left}.wy-text-center{text-align:center}.wy-text-right{text-align:right}.wy-text-large{font-size:120%}.wy-text-normal{font-size:100%}.wy-text-small,small{font-size:80%}.wy-text-strike{text-decoration:line-through}.wy-text-warning{color:#E67E22 !important}a.wy-text-warning:hover{color:#eb9950 !important}.wy-text-info{color:#2980B9 !important}a.wy-text-info:hover{color:#409ad5 !important}.wy-text-success{color:#27AE60 !important}a.wy-text-success:hover{color:#36d278 !important}.wy-text-danger{color:#E74C3C !important}a.wy-text-danger:hover{color:#ed7669 !important}.wy-text-neutral{color:#404040 !important}a.wy-text-neutral:hover{color:#595959 !important}h1,h2,.rst-content .toctree-wrapper p.caption,h3,h4,h5,h6,legend{margin-top:0;font-weight:700;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif}p{line-height:24px;margin:0;font-size:16px;margin-bottom:24px}h1{font-size:175%}h2,.rst-content .toctree-wrapper p.caption{font-size:150%}h3{font-size:125%}h4{font-size:115%}h5{font-size:110%}h6{font-size:100%}hr{display:block;height:1px;border:0;border-top:1px solid #e1e4e5;margin:24px 0;padding:0}code,.rst-content tt,.rst-content code{white-space:nowrap;max-width:100%;background:#fff;border:solid 1px #e1e4e5;font-size:75%;padding:0 5px;font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;color:#E74C3C;overflow-x:auto}code.code-large,.rst-content tt.code-large{font-size:90%}.wy-plain-list-disc,.rst-content .section ul,.rst-content .toctree-wrapper ul,article ul{list-style:disc;line-height:24px;margin-bottom:24px}.wy-plain-list-disc li,.rst-content .section ul li,.rst-content .toctree-wrapper ul li,article ul li{list-style:disc;margin-left:24px}.wy-plain-list-disc li p:last-child,.rst-content .section ul li p:last-child,.rst-content .toctree-wrapper ul li p:last-child,article ul li p:last-child{margin-bottom:0}.wy-plain-list-disc li ul,.rst-content .section ul li ul,.rst-content .toctree-wrapper ul li ul,article ul li ul{margin-bottom:0}.wy-plain-list-disc li li,.rst-content .section ul li li,.rst-content .toctree-wrapper ul li li,article ul li li{list-style:circle}.wy-plain-list-disc li li li,.rst-content .section ul li li li,.rst-content .toctree-wrapper ul li li li,article ul li li li{list-style:square}.wy-plain-list-disc li ol li,.rst-content .section ul li ol li,.rst-content .toctree-wrapper ul li ol li,article ul li ol li{list-style:decimal}.wy-plain-list-decimal,.rst-content .section ol,.rst-content ol.arabic,article ol{list-style:decimal;line-height:24px;margin-bottom:24px}.wy-plain-list-decimal li,.rst-content .section ol li,.rst-content ol.arabic li,article ol li{list-style:decimal;margin-left:24px}.wy-plain-list-decimal li p:last-child,.rst-content .section ol li p:last-child,.rst-content ol.arabic li p:last-child,article ol li p:last-child{margin-bottom:0}.wy-plain-list-decimal li ul,.rst-content .section ol li ul,.rst-content ol.arabic li ul,article ol li ul{margin-bottom:0}.wy-plain-list-decimal li ul li,.rst-content .section ol li ul li,.rst-content ol.arabic li ul li,article ol li ul li{list-style:disc}.codeblock-example{border:1px solid #e1e4e5;border-bottom:none;padding:24px;padding-top:48px;font-weight:500;background:#fff;position:relative}.codeblock-example:after{content:"Example";position:absolute;top:0px;left:0px;background:#9B59B6;color:#fff;padding:6px 12px}.codeblock-example.prettyprint-example-only{border:1px solid #e1e4e5;margin-bottom:24px}.codeblock,pre.literal-block,.rst-content .literal-block,.rst-content pre.literal-block,div[class^='highlight']{border:1px solid #e1e4e5;padding:0px;overflow-x:auto;background:#fff;margin:1px 0 24px 0}.codeblock div[class^='highlight'],pre.literal-block div[class^='highlight'],.rst-content .literal-block div[class^='highlight'],div[class^='highlight'] div[class^='highlight']{border:none;background:none;margin:0}div[class^='highlight'] td.code{width:100%}.linenodiv pre{border-right:solid 1px #e6e9ea;margin:0;padding:12px 12px;font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:12px;line-height:1.5;color:#d9d9d9}div[class^='highlight'] pre{white-space:pre;margin:0;padding:12px 12px;font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:12px;line-height:1.5;display:block;overflow:auto;color:#404040}@media print{.codeblock,pre.literal-block,.rst-content .literal-block,.rst-content pre.literal-block,div[class^='highlight'],div[class^='highlight'] pre{white-space:pre-wrap}}.hll{background-color:#ffc;margin:0 -12px;padding:0 12px;display:block}.c{color:#998;font-style:italic}.err{color:#a61717;background-color:#e3d2d2}.k{font-weight:bold}.o{font-weight:bold}.cm{color:#998;font-style:italic}.cp{color:#999;font-weight:bold}.c1{color:#998;font-style:italic}.cs{color:#999;font-weight:bold;font-style:italic}.gd{color:#000;background-color:#fdd}.gd .x{color:#000;background-color:#faa}.ge{font-style:italic}.gr{color:#a00}.gh{color:#999}.gi{color:#000;background-color:#dfd}.gi .x{color:#000;background-color:#afa}.go{color:#888}.gp{color:#555}.gs{font-weight:bold}.gu{color:purple;font-weight:bold}.gt{color:#a00}.kc{font-weight:bold}.kd{font-weight:bold}.kn{font-weight:bold}.kp{font-weight:bold}.kr{font-weight:bold}.kt{color:#458;font-weight:bold}.m{color:#099}.s{color:#d14}.n{color:#333}.na{color:teal}.nb{color:#0086b3}.nc{color:#458;font-weight:bold}.no{color:teal}.ni{color:purple}.ne{color:#900;font-weight:bold}.nf{color:#900;font-weight:bold}.nn{color:#555}.nt{color:navy}.nv{color:teal}.ow{font-weight:bold}.w{color:#bbb}.mf{color:#099}.mh{color:#099}.mi{color:#099}.mo{color:#099}.sb{color:#d14}.sc{color:#d14}.sd{color:#d14}.s2{color:#d14}.se{color:#d14}.sh{color:#d14}.si{color:#d14}.sx{color:#d14}.sr{color:#009926}.s1{color:#d14}.ss{color:#990073}.bp{color:#999}.vc{color:teal}.vg{color:teal}.vi{color:teal}.il{color:#099}.gc{color:#999;background-color:#EAF2F5}.wy-breadcrumbs li{display:inline-block}.wy-breadcrumbs li.wy-breadcrumbs-aside{float:right}.wy-breadcrumbs li a{display:inline-block;padding:5px}.wy-breadcrumbs li a:first-child{padding-left:0}.wy-breadcrumbs li code,.wy-breadcrumbs li .rst-content tt,.rst-content .wy-breadcrumbs li tt{padding:5px;border:none;background:none}.wy-breadcrumbs li code.literal,.wy-breadcrumbs li .rst-content tt.literal,.rst-content .wy-breadcrumbs li tt.literal{color:#404040}.wy-breadcrumbs-extra{margin-bottom:0;color:#b3b3b3;font-size:80%;display:inline-block}@media screen and (max-width: 480px){.wy-breadcrumbs-extra{display:none}.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}@media print{.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}.wy-affix{position:fixed;top:1.618em}.wy-menu a:hover{text-decoration:none}.wy-menu-horiz{*zoom:1}.wy-menu-horiz:before,.wy-menu-horiz:after{display:table;content:""}.wy-menu-horiz:after{clear:both}.wy-menu-horiz ul,.wy-menu-horiz li{display:inline-block}.wy-menu-horiz li:hover{background:rgba(255,255,255,0.1)}.wy-menu-horiz li.divide-left{border-left:solid 1px #404040}.wy-menu-horiz li.divide-right{border-right:solid 1px #404040}.wy-menu-horiz a{height:32px;display:inline-block;line-height:32px;padding:0 16px}.wy-menu-vertical{width:300px}.wy-menu-vertical header,.wy-menu-vertical p.caption{height:32px;display:inline-block;line-height:32px;padding:0 1.618em;margin-bottom:0;display:block;font-weight:bold;text-transform:uppercase;font-size:80%;color:#555;white-space:nowrap}.wy-menu-vertical ul{margin-bottom:0}.wy-menu-vertical li.divide-top{border-top:solid 1px #404040}.wy-menu-vertical li.divide-bottom{border-bottom:solid 1px #404040}.wy-menu-vertical li.current{background:#e3e3e3}.wy-menu-vertical li.current a{color:gray;border-right:solid 1px #c9c9c9;padding:0.4045em 2.427em}.wy-menu-vertical li.current a:hover{background:#d6d6d6}.wy-menu-vertical li code,.wy-menu-vertical li .rst-content tt,.rst-content .wy-menu-vertical li tt{border:none;background:inherit;color:inherit;padding-left:0;padding-right:0}.wy-menu-vertical li span.toctree-expand{display:block;float:left;margin-left:-1.2em;font-size:0.8em;line-height:1.6em;color:#4d4d4d}.wy-menu-vertical li.on a,.wy-menu-vertical li.current>a{color:#404040;padding:0.4045em 1.618em;font-weight:bold;position:relative;background:#fcfcfc;border:none;border-bottom:solid 1px #c9c9c9;border-top:solid 1px #c9c9c9;padding-left:1.618em -4px}.wy-menu-vertical li.on a:hover,.wy-menu-vertical li.current>a:hover{background:#fcfcfc}.wy-menu-vertical li.on a:hover span.toctree-expand,.wy-menu-vertical li.current>a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li.current>a span.toctree-expand{display:block;font-size:0.8em;line-height:1.6em;color:#333}.wy-menu-vertical li.toctree-l1.current li.toctree-l2>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3>ul{display:none}.wy-menu-vertical li.toctree-l1.current li.toctree-l2.current>ul,.wy-menu-vertical li.toctree-l2.current li.toctree-l3.current>ul{display:block}.wy-menu-vertical li.toctree-l2.current>a{background:#c9c9c9;padding:0.4045em 2.427em}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{display:block;background:#c9c9c9;padding:0.4045em 4.045em}.wy-menu-vertical li.toctree-l2 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l2 span.toctree-expand{color:#a3a3a3}.wy-menu-vertical li.toctree-l3{font-size:0.9em}.wy-menu-vertical li.toctree-l3.current>a{background:#bdbdbd;padding:0.4045em 4.045em}.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{display:block;background:#bdbdbd;padding:0.4045em 5.663em;border-top:none;border-bottom:none}.wy-menu-vertical li.toctree-l3 a:hover span.toctree-expand{color:gray}.wy-menu-vertical li.toctree-l3 span.toctree-expand{color:#969696}.wy-menu-vertical li.toctree-l4{font-size:0.9em}.wy-menu-vertical li.current ul{display:block}.wy-menu-vertical li ul{margin-bottom:0;display:none}.wy-menu-vertical .local-toc li ul{display:block}.wy-menu-vertical li ul li a{margin-bottom:0;color:#b3b3b3;font-weight:normal}.wy-menu-vertical a{display:inline-block;line-height:18px;padding:0.4045em 1.618em;display:block;position:relative;font-size:90%;color:#b3b3b3}.wy-menu-vertical a:hover{background-color:#4e4a4a;cursor:pointer}.wy-menu-vertical a:hover span.toctree-expand{color:#b3b3b3}.wy-menu-vertical a:active{background-color:#2980B9;cursor:pointer;color:#fff}.wy-menu-vertical a:active span.toctree-expand{color:#fff}.wy-side-nav-search{display:block;width:300px;padding:0.809em;margin-bottom:0.809em;z-index:200;background-color:#2980B9;text-align:center;padding:0.809em;display:block;color:#fcfcfc;margin-bottom:0.809em}.wy-side-nav-search input[type=text]{width:100%;border-radius:50px;padding:6px 12px;border-color:#2472a4}.wy-side-nav-search img{display:block;margin:auto auto 0.809em auto;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-side-nav-search>a,.wy-side-nav-search .wy-dropdown>a{color:#fcfcfc;font-size:100%;font-weight:bold;display:inline-block;padding:4px 6px;margin-bottom:0.809em}.wy-side-nav-search>a:hover,.wy-side-nav-search .wy-dropdown>a:hover{background:rgba(255,255,255,0.1)}.wy-side-nav-search>a img.logo,.wy-side-nav-search .wy-dropdown>a img.logo{display:block;margin:0 auto;height:auto;width:auto;border-radius:0;max-width:100%;background:transparent}.wy-side-nav-search>a.icon img.logo,.wy-side-nav-search .wy-dropdown>a.icon img.logo{margin-top:0.85em}.wy-side-nav-search>div.version{margin-top:-0.4045em;margin-bottom:0.809em;font-weight:normal;color:rgba(255,255,255,0.3)}.wy-nav .wy-menu-vertical header{color:#2980B9}.wy-nav .wy-menu-vertical a{color:#b3b3b3}.wy-nav .wy-menu-vertical a:hover{background-color:#2980B9;color:#fff}[data-menu-wrap]{-webkit-transition:all 0.2s ease-in;-moz-transition:all 0.2s ease-in;transition:all 0.2s ease-in;position:absolute;opacity:1;width:100%;opacity:0}[data-menu-wrap].move-center{left:0;right:auto;opacity:1}[data-menu-wrap].move-left{right:auto;left:-100%;opacity:0}[data-menu-wrap].move-right{right:-100%;left:auto;opacity:0}.wy-body-for-nav{background:left repeat-y #fcfcfc;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoxOERBMTRGRDBFMUUxMUUzODUwMkJCOThDMEVFNURFMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoxOERBMTRGRTBFMUUxMUUzODUwMkJCOThDMEVFNURFMCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjE4REExNEZCMEUxRTExRTM4NTAyQkI5OEMwRUU1REUwIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjE4REExNEZDMEUxRTExRTM4NTAyQkI5OEMwRUU1REUwIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+EwrlwAAAAA5JREFUeNpiMDU0BAgwAAE2AJgB9BnaAAAAAElFTkSuQmCC);background-size:300px 1px}.wy-grid-for-nav{position:absolute;width:100%;height:100%}.wy-nav-side{position:fixed;top:0;bottom:0;left:0;padding-bottom:2em;width:300px;overflow-x:hidden;overflow-y:hidden;min-height:100%;background:#343131;z-index:200}.wy-side-scroll{width:320px;position:relative;overflow-x:hidden;overflow-y:scroll;height:100%}.wy-nav-top{display:none;background:#2980B9;color:#fff;padding:0.4045em 0.809em;position:relative;line-height:50px;text-align:center;font-size:100%;*zoom:1}.wy-nav-top:before,.wy-nav-top:after{display:table;content:""}.wy-nav-top:after{clear:both}.wy-nav-top a{color:#fff;font-weight:bold}.wy-nav-top img{margin-right:12px;height:45px;width:45px;background-color:#2980B9;padding:5px;border-radius:100%}.wy-nav-top i{font-size:30px;float:left;cursor:pointer}.wy-nav-content-wrap{margin-left:300px;background:#fcfcfc;min-height:100%}.wy-nav-content{padding:1.618em 3.236em;height:100%;max-width:800px;margin:auto}.wy-body-mask{position:fixed;width:100%;height:100%;background:rgba(0,0,0,0.2);display:none;z-index:499}.wy-body-mask.on{display:block}footer{color:#999}footer p{margin-bottom:12px}footer span.commit code,footer span.commit .rst-content tt,.rst-content footer span.commit tt{padding:0px;font-family:Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:1em;background:none;border:none;color:#999}.rst-footer-buttons{*zoom:1}.rst-footer-buttons:before,.rst-footer-buttons:after{display:table;content:""}.rst-footer-buttons:after{clear:both}#search-results .search li{margin-bottom:24px;border-bottom:solid 1px #e1e4e5;padding-bottom:24px}#search-results .search li:first-child{border-top:solid 1px #e1e4e5;padding-top:24px}#search-results .search li a{font-size:120%;margin-bottom:12px;display:inline-block}#search-results .context{color:gray;font-size:90%}@media screen and (max-width: 768px){.wy-body-for-nav{background:#fcfcfc}.wy-nav-top{display:block}.wy-nav-side{left:-300px}.wy-nav-side.shift{width:85%;left:0}.wy-side-scroll{width:auto}.wy-side-nav-search{width:auto}.wy-menu.wy-menu-vertical{width:auto}.wy-nav-content-wrap{margin-left:0}.wy-nav-content-wrap .wy-nav-content{padding:1.618em}.wy-nav-content-wrap.shift{position:fixed;min-width:100%;left:85%;top:0;height:100%;overflow:hidden}}@media screen and (min-width: 1400px){.wy-nav-content-wrap{background:rgba(0,0,0,0.05)}.wy-nav-content{margin:0;background:#fcfcfc}}@media print{.rst-versions,footer,.wy-nav-side{display:none}.wy-nav-content-wrap{margin-left:0}}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;border-top:solid 10px #343131;font-family:"Lato","proxima-nova","Helvetica Neue",Arial,sans-serif;z-index:400}.rst-versions a{color:#2980B9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27AE60;*zoom:1}.rst-versions .rst-current-version:before,.rst-versions .rst-current-version:after{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-versions .rst-current-version .fa,.rst-versions .rst-current-version .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .rst-versions .rst-current-version span.toctree-expand,.rst-versions .rst-current-version .rst-content .admonition-title,.rst-content .rst-versions .rst-current-version .admonition-title,.rst-versions .rst-current-version .rst-content h1 .headerlink,.rst-content h1 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h2 .headerlink,.rst-content h2 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h3 .headerlink,.rst-content h3 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h4 .headerlink,.rst-content h4 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h5 .headerlink,.rst-content h5 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content h6 .headerlink,.rst-content h6 .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content dl dt .headerlink,.rst-content dl dt .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content p.caption .headerlink,.rst-content p.caption .rst-versions .rst-current-version .headerlink,.rst-versions .rst-current-version .rst-content tt.download span:first-child,.rst-content tt.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .rst-content code.download span:first-child,.rst-content code.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .icon{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#E74C3C;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#F1C40F;color:#000}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:gray;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:solid 1px #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px}.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge .rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width: 768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}img{width:100%;height:auto}}.rst-content img{max-width:100%;height:auto !important}.rst-content div.figure{margin-bottom:24px}.rst-content div.figure p.caption{font-style:italic}.rst-content div.figure.align-center{text-align:center}.rst-content .section>img,.rst-content .section>a>img{margin-bottom:24px}.rst-content blockquote{margin-left:24px;line-height:24px;margin-bottom:24px}.rst-content .note .last,.rst-content .attention .last,.rst-content .caution .last,.rst-content .danger .last,.rst-content .error .last,.rst-content .hint .last,.rst-content .important .last,.rst-content .tip .last,.rst-content .warning .last,.rst-content .seealso .last,.rst-content .admonition-todo .last{margin-bottom:0}.rst-content .admonition-title:before{margin-right:4px}.rst-content .admonition table{border-color:rgba(0,0,0,0.1)}.rst-content .admonition table td,.rst-content .admonition table th{background:transparent !important;border-color:rgba(0,0,0,0.1) !important}.rst-content .section ol.loweralpha,.rst-content .section ol.loweralpha li{list-style:lower-alpha}.rst-content .section ol.upperalpha,.rst-content .section ol.upperalpha li{list-style:upper-alpha}.rst-content .section ol p,.rst-content .section ul p{margin-bottom:12px}.rst-content .line-block{margin-left:24px}.rst-content .topic-title{font-weight:bold;margin-bottom:12px}.rst-content .toc-backref{color:#404040}.rst-content .align-right{float:right;margin:0px 0px 24px 24px}.rst-content .align-left{float:left;margin:0px 24px 24px 0px}.rst-content .align-center{margin:auto;display:block}.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content .toctree-wrapper p.caption .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content dl dt .headerlink,.rst-content p.caption .headerlink{display:none;visibility:hidden;font-size:14px}.rst-content h1 .headerlink:after,.rst-content h2 .headerlink:after,.rst-content .toctree-wrapper p.caption .headerlink:after,.rst-content h3 .headerlink:after,.rst-content h4 .headerlink:after,.rst-content h5 .headerlink:after,.rst-content h6 .headerlink:after,.rst-content dl dt .headerlink:after,.rst-content p.caption .headerlink:after{visibility:visible;content:"";font-family:FontAwesome;display:inline-block}.rst-content h1:hover .headerlink,.rst-content h2:hover .headerlink,.rst-content .toctree-wrapper p.caption:hover .headerlink,.rst-content h3:hover .headerlink,.rst-content h4:hover .headerlink,.rst-content h5:hover .headerlink,.rst-content h6:hover .headerlink,.rst-content dl dt:hover .headerlink,.rst-content p.caption:hover .headerlink{display:inline-block}.rst-content .sidebar{float:right;width:40%;display:block;margin:0 0 24px 24px;padding:24px;background:#f3f6f6;border:solid 1px #e1e4e5}.rst-content .sidebar p,.rst-content .sidebar ul,.rst-content .sidebar dl{font-size:90%}.rst-content .sidebar .last{margin-bottom:0}.rst-content .sidebar .sidebar-title{display:block;font-family:"Roboto Slab","ff-tisa-web-pro","Georgia",Arial,sans-serif;font-weight:bold;background:#e1e4e5;padding:6px 12px;margin:-24px;margin-bottom:24px;font-size:100%}.rst-content .highlighted{background:#F1C40F;display:inline-block;font-weight:bold;padding:0 6px}.rst-content .footnote-reference,.rst-content .citation-reference{vertical-align:super;font-size:90%}.rst-content table.docutils.citation,.rst-content table.docutils.footnote{background:none;border:none;color:#999}.rst-content table.docutils.citation td,.rst-content table.docutils.citation tr,.rst-content table.docutils.footnote td,.rst-content table.docutils.footnote tr{border:none;background-color:transparent !important;white-space:normal}.rst-content table.docutils.citation td.label,.rst-content table.docutils.footnote td.label{padding-left:0;padding-right:0;vertical-align:top}.rst-content table.docutils.citation tt,.rst-content table.docutils.citation code,.rst-content table.docutils.footnote tt,.rst-content table.docutils.footnote code{color:#555}.rst-content table.field-list{border:none}.rst-content table.field-list td{border:none;padding-top:5px}.rst-content table.field-list td>strong{display:inline-block;margin-top:3px}.rst-content table.field-list .field-name{padding-right:10px;text-align:left;white-space:nowrap}.rst-content table.field-list .field-body{text-align:left;padding-left:0}.rst-content tt,.rst-content tt,.rst-content code{color:#000;padding:2px 5px}.rst-content tt big,.rst-content tt em,.rst-content tt big,.rst-content code big,.rst-content tt em,.rst-content code em{font-size:100% !important;line-height:normal}.rst-content tt.literal,.rst-content tt.literal,.rst-content code.literal{color:#E74C3C}.rst-content tt.xref,a .rst-content tt,.rst-content tt.xref,.rst-content code.xref,a .rst-content tt,a .rst-content code{font-weight:bold;color:#404040}.rst-content a tt,.rst-content a tt,.rst-content a code{color:#2980B9}.rst-content dl{margin-bottom:24px}.rst-content dl dt{font-weight:bold}.rst-content dl p,.rst-content dl table,.rst-content dl ul,.rst-content dl ol{margin-bottom:12px !important}.rst-content dl dd{margin:0 0 12px 24px}.rst-content dl:not(.docutils){margin-bottom:24px}.rst-content dl:not(.docutils) dt{display:inline-block;margin:6px 0;font-size:90%;line-height:normal;background:#e7f2fa;color:#2980B9;border-top:solid 3px #6ab0de;padding:6px;position:relative}.rst-content dl:not(.docutils) dt:before{color:#6ab0de}.rst-content dl:not(.docutils) dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dl dt{margin-bottom:6px;border:none;border-left:solid 3px #ccc;background:#f0f0f0;color:#555}.rst-content dl:not(.docutils) dl dt .headerlink{color:#404040;font-size:100% !important}.rst-content dl:not(.docutils) dt:first-child{margin-top:0}.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) tt,.rst-content dl:not(.docutils) code{font-weight:bold}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname,.rst-content dl:not(.docutils) tt.descclassname,.rst-content dl:not(.docutils) code.descclassname{background-color:transparent;border:none;padding:0;font-size:100% !important}.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) tt.descname,.rst-content dl:not(.docutils) code.descname{font-weight:bold}.rst-content dl:not(.docutils) .optional{display:inline-block;padding:0 4px;color:#000;font-weight:bold}.rst-content dl:not(.docutils) .property{display:inline-block;padding-right:8px}.rst-content .viewcode-link,.rst-content .viewcode-back{display:inline-block;color:#27AE60;font-size:80%;padding-left:24px}.rst-content .viewcode-back{display:block;float:right}.rst-content p.rubric{margin-bottom:12px;font-weight:bold}.rst-content tt.download,.rst-content code.download{background:inherit;padding:inherit;font-family:inherit;font-size:inherit;color:inherit;border:inherit;white-space:inherit}.rst-content tt.download span:first-child:before,.rst-content code.download span:first-child:before{margin-right:4px}@media screen and (max-width: 480px){.rst-content .sidebar{width:100%}}span[id*='MathJax-Span']{color:#404040}.math{text-align:center}@font-face{font-family:"Inconsolata";font-style:normal;font-weight:400;src:local("Inconsolata"),local("Inconsolata-Regular"),url(../fonts/Inconsolata-Regular.ttf) format("truetype")}@font-face{font-family:"Inconsolata";font-style:normal;font-weight:700;src:local("Inconsolata Bold"),local("Inconsolata-Bold"),url(../fonts/Inconsolata-Bold.ttf) format("truetype")}@font-face{font-family:"Lato";font-style:normal;font-weight:400;src:local("Lato Regular"),local("Lato-Regular"),url(../fonts/Lato-Regular.ttf) format("truetype")}@font-face{font-family:"Lato";font-style:normal;font-weight:700;src:local("Lato Bold"),local("Lato-Bold"),url(../fonts/Lato-Bold.ttf) format("truetype")}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:400;src:local("Roboto Slab Regular"),local("RobotoSlab-Regular"),url(../fonts/RobotoSlab-Regular.ttf) format("truetype")}@font-face{font-family:"Roboto Slab";font-style:normal;font-weight:700;src:local("Roboto Slab Bold"),local("RobotoSlab-Bold"),url(../fonts/RobotoSlab-Bold.ttf) format("truetype")} +/*# sourceMappingURL=theme.css.map */ diff --git a/docs/build/html/_static/doctools.js b/docs/build/html/_static/doctools.js new file mode 100644 index 0000000000..8163495635 --- /dev/null +++ b/docs/build/html/_static/doctools.js @@ -0,0 +1,287 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s == 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node) { + if (node.nodeType == 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { + var span = document.createElement("span"); + span.className = className; + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this); + }); + } + } + return this.each(function() { + highlight(this); + }); +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated == 'undefined') + return string; + return (typeof translated == 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated == 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) == 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this == '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); \ No newline at end of file diff --git a/docs/build/html/_static/down-pressed.png b/docs/build/html/_static/down-pressed.png new file mode 100644 index 0000000000..7c30d004b7 Binary files /dev/null and b/docs/build/html/_static/down-pressed.png differ diff --git a/docs/build/html/_static/down.png b/docs/build/html/_static/down.png new file mode 100644 index 0000000000..f48098a43b Binary files /dev/null and b/docs/build/html/_static/down.png differ diff --git a/docs/build/html/_static/file.png b/docs/build/html/_static/file.png new file mode 100644 index 0000000000..254c60bfbe Binary files /dev/null and b/docs/build/html/_static/file.png differ diff --git a/docs/build/html/_static/fonts/Inconsolata-Bold.ttf b/docs/build/html/_static/fonts/Inconsolata-Bold.ttf new file mode 100644 index 0000000000..58c9fef3a0 Binary files /dev/null and b/docs/build/html/_static/fonts/Inconsolata-Bold.ttf differ diff --git a/docs/build/html/_static/fonts/Inconsolata-Regular.ttf b/docs/build/html/_static/fonts/Inconsolata-Regular.ttf new file mode 100644 index 0000000000..a87ffba6be Binary files /dev/null and b/docs/build/html/_static/fonts/Inconsolata-Regular.ttf differ diff --git a/docs/build/html/_static/fonts/Lato-Bold.ttf b/docs/build/html/_static/fonts/Lato-Bold.ttf new file mode 100644 index 0000000000..74343694e2 Binary files /dev/null and b/docs/build/html/_static/fonts/Lato-Bold.ttf differ diff --git a/docs/build/html/_static/fonts/Lato-Regular.ttf b/docs/build/html/_static/fonts/Lato-Regular.ttf new file mode 100644 index 0000000000..04ea8efb13 Binary files /dev/null and b/docs/build/html/_static/fonts/Lato-Regular.ttf differ diff --git a/docs/build/html/_static/fonts/RobotoSlab-Bold.ttf b/docs/build/html/_static/fonts/RobotoSlab-Bold.ttf new file mode 100644 index 0000000000..df5d1df273 Binary files /dev/null and b/docs/build/html/_static/fonts/RobotoSlab-Bold.ttf differ diff --git a/docs/build/html/_static/fonts/RobotoSlab-Regular.ttf b/docs/build/html/_static/fonts/RobotoSlab-Regular.ttf new file mode 100644 index 0000000000..eb52a79073 Binary files /dev/null and b/docs/build/html/_static/fonts/RobotoSlab-Regular.ttf differ diff --git a/docs/build/html/_static/fonts/fontawesome-webfont.eot b/docs/build/html/_static/fonts/fontawesome-webfont.eot new file mode 100644 index 0000000000..84677bc0c5 Binary files /dev/null and b/docs/build/html/_static/fonts/fontawesome-webfont.eot differ diff --git a/docs/build/html/_static/fonts/fontawesome-webfont.svg b/docs/build/html/_static/fonts/fontawesome-webfont.svg new file mode 100644 index 0000000000..d907b25ae6 --- /dev/null +++ b/docs/build/html/_static/fonts/fontawesome-webfont.svg @@ -0,0 +1,520 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_static/fonts/fontawesome-webfont.ttf b/docs/build/html/_static/fonts/fontawesome-webfont.ttf new file mode 100644 index 0000000000..96a3639cdd Binary files /dev/null and b/docs/build/html/_static/fonts/fontawesome-webfont.ttf differ diff --git a/docs/build/html/_static/fonts/fontawesome-webfont.woff b/docs/build/html/_static/fonts/fontawesome-webfont.woff new file mode 100644 index 0000000000..628b6a52a8 Binary files /dev/null and b/docs/build/html/_static/fonts/fontawesome-webfont.woff differ diff --git a/docs/build/html/_static/irs.png b/docs/build/html/_static/irs.png new file mode 100644 index 0000000000..11ee25f144 Binary files /dev/null and b/docs/build/html/_static/irs.png differ diff --git a/docs/build/html/_static/jquery-1.11.1.js b/docs/build/html/_static/jquery-1.11.1.js new file mode 100644 index 0000000000..d4b67f7e6c --- /dev/null +++ b/docs/build/html/_static/jquery-1.11.1.js @@ -0,0 +1,10308 @@ +/*! + * jQuery JavaScript Library v1.11.1 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-05-01T17:42Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper window is present, + // execute the factory and get jQuery + // For environments that do not inherently posses a window with a document + // (such as Node.js), expose a jQuery-making factory as module.exports + // This accentuates the need for the creation of a real window + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +// + +var deletedIds = []; + +var slice = deletedIds.slice; + +var concat = deletedIds.concat; + +var push = deletedIds.push; + +var indexOf = deletedIds.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "1.11.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1, IE<9 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( support.ownLast ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1, IE<9 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + while ( j < len ) { + first[ i++ ] = second[ j++ ]; + } + + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: function() { + return +( new Date() ); + }, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v1.10.19 + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-04-18 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== strundefined && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, + doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", function() { + setDocument(); + }, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", function() { + setDocument(); + }); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { + div.innerHTML = "
"; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowclip^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !(--remaining) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * Clean-up method for dom ready events + */ +function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } +} + +/** + * The ready event handler and self cleanup method + */ +function completed() { + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + + +var strundefined = typeof undefined; + + + +// Support: IE<9 +// Iteration over object's inherited properties before its own +var i; +for ( i in jQuery( support ) ) { + break; +} +support.ownLast = i !== "0"; + +// Note: most support tests are defined in their respective modules. +// false until the test is run +support.inlineBlockNeedsLayout = false; + +// Execute ASAP in case we need to set body.style.zoom +jQuery(function() { + // Minified: var a,b,c,d + var val, div, body, container; + + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { + // Return for frameset docs that don't have a body + return; + } + + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); + + if ( typeof div.style.zoom !== strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; + + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); +}); + + + + +(function() { + var div = document.createElement( "div" ); + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( elem ) { + var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], + nodeType = +elem.nodeType || 1; + + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : + + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute("classid") === noData; +}; + + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + +function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[0], + attrs = elem && elem.attributes; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; +}; +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + // Minified: var a,b,c + var input = document.createElement( "input" ), + div = document.createElement( "div" ), + fragment = document.createDocumentFragment(); + + // Setup + div.innerHTML = "
a"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; + + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); + div.innerHTML = ""; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + support.noCloneEvent = true; + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } +})(); + + +(function() { + var i, eventName, + div = document.createElement( "div" ); + + // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) + for ( i in { submit: true, change: true, focusin: true }) { + eventName = "on" + i; + + if ( !(support[ i + "Bubbles" ] = eventName in window) ) { + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!support.noCloneEvent || !support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + deletedIds.push( id ); + } + } + } + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optmization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "