diff --git a/docs/build/html/_sources/tutorial.txt b/docs/build/html/_sources/tutorial.txt index d30268c2b8..29d50207ba 100644 --- a/docs/build/html/_sources/tutorial.txt +++ b/docs/build/html/_sources/tutorial.txt @@ -320,6 +320,7 @@ logic. .. sourcecode:: kotlin + val time = tx.time for (group in groups) { when (command.value) { is Commands.Move -> { @@ -333,8 +334,9 @@ logic. is Commands.Redeem -> { val input = group.inputs.single() val received = tx.outStates.sumCashBy(input.owner) + if (time == null) throw IllegalArgumentException("Redemption transactions must be timestamped") requireThat { - "the paper must have matured" by (input.maturityDate < tx.time) + "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 group.outputs.isEmpty() "the transaction is signed by the owner of the CP" by (command.signers.contains(input.owner)) @@ -343,12 +345,13 @@ logic. is Commands.Issue -> { val output = group.outputs.single() + if (time == null) throw IllegalArgumentException("Issuance transactions must be timestamped") requireThat { // Don't allow people to issue commercial paper under other entities identities. "the issuance is signed by the claimed issuer of the paper" by (command.signers.contains(output.issuance.institution.owningKey)) "the face value is not zero" by (output.faceValue.pennies > 0) - "the maturity date is not in the past" by (output.maturityDate > tx.time) + "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. "there is no input state" by group.inputs.isEmpty() } @@ -361,6 +364,7 @@ logic. .. sourcecode:: java + Instant time = tx.getTime(); // Can be null/missing. for (InOutGroup group : groups) { List inputs = group.getInputs(); List outputs = group.getOutputs(); @@ -381,9 +385,11 @@ logic. throw new IllegalStateException("Failed requirement: the output state is the same as the input state except for owner"); } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Redeem) { Amount received = CashKt.sumCashOrNull(inputs); + if (time == null) + throw new IllegalArgumentException("Redemption transactions must be timestamped"); if (received == null) throw new IllegalStateException("Failed requirement: no cash being redeemed"); - if (input.getMaturityDate().isAfter(tx.getTime())) + if (input.getMaturityDate().isAfter(time)) throw new IllegalStateException("Failed requirement: the paper must have matured"); if (!input.getFaceValue().equals(received)) throw new IllegalStateException("Failed requirement: the received amount equals the face value"); @@ -396,6 +402,14 @@ logic. 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 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 diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js index c489aa57f9..56a523ebb4 100644 --- a/docs/build/html/searchindex.js +++ b/docs/build/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({envversion:46,filenames:["getting-set-up","index","inthebox","overview","roadmap","tutorial"],objects:{},objnames:{},objtypes:{},terms:{"8u45":0,"boolean":5,"break":5,"byte":3,"case":[3,4,5],"catch":0,"class":[],"default":[0,5],"final":[4,5],"function":[],"import":[0,3,5],"instanceof":5,"int":5,"new":[3,5],"null":5,"public":[2,3,5],"return":5,"short":5,"static":5,"switch":5,"throw":5,"true":5,"try":[3,5],"var":5,"void":5,abil:[3,5],about:[3,4,5],abov:5,accept:[3,5],accident:5,account:3,actor:5,actual:5,add:5,addit:5,address:[3,5],admin:4,administr:2,advanc:4,affection:5,after:[3,5],again:5,against:5,agre:[0,3],algorithm:[2,3],alic:5,alicegetsback:5,all:[0,3,5],allow:[3,5],almost:5,along:[3,5],alreadi:5,also:[0,3,5],alt:5,alter:5,although:[3,5],alwai:3,amount:[2,5],ani:[3,5],annot:5,anoth:5,anyon:5,anyth:[3,5],anywher:5,api:[2,3,4],appear:[3,5],applic:3,approach:[3,5],arbitrari:[3,5],arbitrarili:3,aren:5,arg:5,argument:[3,5],around:3,arrai:3,articl:3,artifact:5,ask:5,assembl:3,assert:5,asset:3,assist:5,associ:[3,5],assum:5,atom:5,attach:[3,5],attempt:3,audit:3,authenticatedobject:5,author:3,auto:5,autom:5,automat:5,avail:5,await:5,back:5,background:3,backtick:5,bad:5,balanc:5,bankrupt:5,base:3,basic:[3,5],bear:5,becaus:5,becom:5,been:[3,5],befor:[3,5],begin:[3,5],behav:5,behaviour:2,behind:5,benefit:5,beta:0,better:[1,3,5],between:5,beyond:[3,5],bill:5,bind:3,bit:5,bitbucket:0,blah:[],blank:5,block:[3,5],bob:5,bond:5,bookkeep:3,boost:2,both:[3,5],brows:2,bug:2,build:[0,3,5],builder:5,built:5,bunch:5,bundl:3,busi:[3,5],bytecod:[3,5],c25c001e26e3:[],calcul:5,call:[3,5],can:[0,2,3,5],cannot:[3,5],canon:4,carefulli:3,cash:[],cashkt:5,caus:5,center:5,certain:3,cev:0,chain:[3,5],chang:5,check:[],choos:0,claim:[2,3,5],click:0,cmd:5,code:[0,1,2,3,4,5],codebas:5,collect:5,com:0,combin:5,come:3,command:[],commerci:[],commercial_pap:5,commercialpap:[3,5],commercialpapertest:5,common:5,commonli:5,commun:0,companion:5,compar:3,compil:5,complet:[3,5],complex:[3,5],concept:[3,5],concern:5,configur:0,conflict:3,connect:5,consid:[3,5],consist:[2,3],constant:5,construct:5,consum:3,contain:[3,5],content:[3,5],contract:[],contractst:5,contrast:3,contribut:5,control:[0,3,5],copi:5,core:5,correct:5,correctli:[3,5],correspond:5,cost:5,could:5,coupl:[],cours:5,cover:[3,5],cp_program_id:5,craft:[],creat:[3,5],creation:5,crisp:5,crop:3,currenc:[3,5],current:[2,3,5],curv:2,dai:5,data:[],databas:[1,2],date:5,datetim:3,decid:[3,5],declar:5,defin:[],definit:5,delet:5,deliveri:5,demand:3,denomin:3,depend:[0,5],deposit:3,depth:5,deriv:5,describ:[1,5],design:[1,3,5],desir:5,despit:5,destroi:[3,5],destroypaperatredempt:5,detail:[3,5],develop:3,differ:[3,5],digit:[3,5],direct:5,directori:[0,5],dirti:5,disallow:5,disk:4,disput:5,distinguish:5,distribut:[2,3],doc:5,doe:[1,2,3,4,5],doesn:[3,5],dollar:5,domain:5,don:[0,3,5],done:3,doubl:5,doubt:3,down:5,download:0,drive:3,dsl:[4,5],due:[3,5],dummi:5,dummy_pubkey_1:5,duplic:5,durat:5,dynam:[4,5],each:[3,5],easi:5,easier:5,edit:0,editor:0,effect:5,either:5,element:3,ellipt:2,els:5,emb:5,embed:3,emit:5,empti:5,enabl:5,encount:3,end:[3,5],enforc:[3,5],engin:5,english:5,enough:[4,5],ensur:[3,5],enter:5,entir:[3,5],entiti:5,entri:3,envisag:5,equal:5,equival:5,essenti:5,etc:5,even:[3,5],everi:[3,5],everyon:[],everyth:5,evolv:[4,5],exact:5,exactli:[3,5],examin:[3,5],exampl:[4,5],excel:[],except:5,execut:[3,5],exist:[1,3,5],expect:[2,5],expectfailureoftx:5,explain:5,explicitli:[3,5],explor:[0,1,2,4,5],expos:3,express:[3,5],extend:[3,5],extens:5,extern:2,extract:[3,5],extrem:5,face:[3,5],facevalu:5,fact:5,factor:3,fail:5,failur:5,fake:5,fals:5,familiar:[3,5],far:5,favour:5,featur:5,feel:5,few:[3,5],field:5,file:5,filterisinst:5,financi:[1,3],find:3,first:[0,1,4,5],firstli:5,fit:3,fix:3,flexibl:3,follow:5,foo:[],fooutil:5,form:5,formal:5,format:3,four:5,framework:[2,3],free:3,freeform:5,freshli:5,from:[0,3,5],front:5,full:5,fun:5,fundament:[1,5],fungibl:[],futur:[3,4,5],gain:2,gcd:3,gener:5,get:[],getclass:5,getcommand:5,getfacevalu:5,getinput:5,getissu:5,getlegalcontractrefer:5,getmaturityd:5,getoutput:5,getown:5,getprogramref:5,getsign:5,getter:5,gettim:5,getvalu:5,git:0,give:[3,4,5],given:[3,5],global:[3,4,5],goal:[1,2,3],gone:5,good:[4,5],gradl:[0,3],gradlew:0,graph:[3,4,5],green:0,group:[3,5],groupstat:5,guava:3,hack:3,had:5,hand:5,handl:[3,5],happen:5,hash:[2,3,5],hashcod:5,have:[3,4,5],haven:5,heart:5,heavili:3,held:5,hello:[],help:4,her:5,here:[3,5],higher:[0,5],highlight:5,hit:0,hold:3,holder:5,how:3,howev:5,html:[],http:[0,5],idea:[0,2,3,5],ident:[3,5],identifi:3,ietf:3,ignor:5,illegalargumentexcept:5,illegalstateexcept:5,immut:[3,5],implement:[2,3,4,5],implicitli:5,impos:5,improv:[3,4,5],includ:[],independ:5,index:[3,5],individu:5,industri:[1,3],infer:5,infix:5,inform:[3,5],inherit:5,initi:[4,5],inoutgroup:5,input:[3,5],insid:[3,5],instal:0,instanc:[3,5],instant:5,instanti:3,instead:[2,3,5],institut:[3,5],institutionrefer:5,instruct:[],integ:5,integr:2,intellij:[],intend:3,intent:5,interact:3,interest:[4,5],interfac:[1,2,4,5],intern:3,internet:3,interop:3,interpret:3,intersect:5,introduct:3,invalid:5,invari:5,invok:[3,5],involv:5,ipsum:[],isaft:5,isempti:5,isn:5,issu:[3,5],issuanc:5,issuer:5,item:[0,5],iter:5,itself:[3,5],java:[3,5],javacommercialpap:5,javas:[],jdk:[0,5],jetbrain:[0,3],jira:[2,4],join:5,joint:5,junit:[3,5],just:[0,3,4,5],jvm:3,keep:[3,5],kei:[2,3,5],key_mismatch_at_issu:5,keypair:5,keyword:5,kind:[3,4,5],know:3,known:3,kotin:5,kotlin:[],kotlinlang:[],kryo:3,label:5,labori:5,languag:[3,5],later:[2,5],latest:0,latter:5,layer:4,lazili:5,lead:5,learn:[1,4],least:5,ledger:[1,3,4,5],legal:5,legalcontractrefer:5,less:5,let:[3,5],level:5,librari:[3,5],lifecycl:5,lift:4,like:[3,5],likewis:5,limit:[3,5],line:[0,5],list:5,liter:3,littl:5,load:[4,5],local:[0,3],lock:5,logic:[3,5],logo:0,look:5,loop:5,lorem:[],machin:3,made:1,mai:[3,5],main:5,maintain:3,make:5,maker:3,manag:5,mani:[2,3,5],map:5,mark:5,marker:5,market:1,match:[3,5],matur:5,maturityd:5,maximis:3,mean:3,measur:5,mechan:5,medium:[],meet:5,mega_corp:5,mega_corp_kei:5,megacorp:5,menu:0,mere:[3,5],merg:[3,5],messag:[3,5],method:5,might:5,mileston:[],mind:5,mine:3,minimum:3,minu:5,minut:3,mismatch:[],model:[],modif:5,modifi:[0,5],modul:5,monei:5,monetari:5,more:[3,4,5],most:5,move:5,much:[3,5],multi:5,multipl:[3,5],must:[3,5],mutabl:3,name:[3,5],natur:5,necessarili:5,need:[1,3,5],net:5,network:[1,2,4],neutral:2,never:3,next:[0,4,5],nicer:[],node:3,non:3,normal:5,not_matured_at_redempt:5,note:[0,3,5],noth:[3,5],notic:5,notion:[2,3,5],notnul:5,now:[3,5],nugget:5,nullpublickei:5,number:5,obj:5,object:[3,5],obsolet:2,obvious:5,occur:5,octskyward:[],odd:5,off:5,offic:[],often:[3,5],onc:[3,5],onli:[3,5],onto:5,opaqu:3,opaquebyt:5,open:0,openjdk:0,opposit:5,option:5,oracl:0,order:[2,3,5],ordinari:[3,5],org:[0,5],orient:[],origin:5,other:[2,3,5],otherwis:5,our:[3,5],out:[0,3,4,5],outpoint:3,output:[3,5],outsid:5,outstat:5,over:5,overrid:5,overview:[],own:[3,5],owned_bi:5,owner:5,ownership:5,owningkei:5,packet:3,page:4,pai:5,pair:3,paper:[],paper_1:5,parallel:5,paramet:5,parameteris:3,part:[3,5],parti:5,particip:3,pass:[4,5],past:5,path:5,pattern:[3,5],payment:5,peer:2,pend:4,penni:5,peopl:[3,5],perform:[4,5],perhap:5,perman:[3,5],persist:2,perspect:5,piec:[3,5],place:[2,3,4,5],platform:[1,3,4,5],pleas:3,plugin:0,point:[3,5],pointer:3,poor:3,popular:3,possibl:[3,4,5],potenti:3,pound:5,power:3,practic:3,pre:5,preced:5,present:[1,5],press:5,pretti:5,prevent:5,primari:3,primit:5,privaci:[4,5],privat:[3,4,5],probabl:0,problem:5,produc:5,product:[2,5],profit:5,program:[3,5],programref:5,progress:5,project:0,proof:3,propag:5,properti:5,protocol:[2,3,5],prototyp:[1,2,3,4,5],prove:[3,5],provid:[3,5],publickei:5,pull:0,pure:3,purpos:[3,5],put:5,quantiti:[3,5],quickli:5,quit:5,random:3,rapid:2,rate:4,rather:[3,5],rational:3,read:[1,2,3,5],readabl:3,real:[2,5],realiti:5,realli:5,reason:5,receiv:[3,5],recipi:5,record:5,redeem:[3,5],redempt:5,redemptiontim:5,refer:[3,5],refin:3,reflect:5,registri:3,regular:[3,5],reject:5,rel:3,relat:5,relationship:5,releas:4,relev:3,reli:3,relianc:3,remain:5,rememb:5,remov:5,replac:5,replic:3,report:[],repositori:[3,5],repres:[3,5],requir:[],requiresinglecommand:5,requirethat:5,resolut:3,rest:3,restart:0,result:[3,5],reveal:5,rfc:3,right:0,rigid:3,roadmap:[],root:5,rule:5,run:[0,3,5],safe:[3,5],sai:[3,5],same:[3,5],sandbox:[2,3,4,5],save:5,scala:[3,5],scalabl:[3,4,5],scene:5,scope:[3,5],screen:0,script:[3,5],seal:[],seamless:3,search:[0,5],second:5,secp256r1:2,section:5,secur:3,securehash:5,see:5,seen:5,select:[0,5],semi:3,send:3,sens:[],separ:5,serial:[2,5],serialis:[2,3],serializablewithkryo:5,serializeablewithkryo:5,set:[],setter:5,sever:[3,5],sha256:5,sha:3,share:[1,3,5],she:5,shortcut:2,shorthand:5,should:[0,2,3,5],show:[0,3,5],shown:5,sig:5,sign:[2,3,5],signatur:[2,3,5],signer:5,similar:[3,5],similarli:5,simpl:[4,5],simpler:3,simpli:5,simplifi:[2,3,5],simultan:5,singl:[3,5],singleornul:[],singleton:5,site:4,size:5,slight:5,slightli:5,small:[2,3,5],smart:2,snippet:5,softwar:2,sold:5,solv:5,some:[2,3,4,5],someon:5,someprofit:5,someth:[4,5],sometim:[3,5],somewhat:3,somewher:5,sort:3,sound:5,space:5,specif:[3,5],specifi:[2,5],spend:[3,5],split:[3,5],src:5,stage:[4,5],stai:3,standard:[3,5],standardis:[3,5],start:[],state:[],stateless:3,statement:5,stateref:3,step:5,still:[3,5],storag:[3,4],store:5,straightforward:5,string:5,strong:3,structur:[2,3,5],studi:5,sub:4,subgroup:[3,4],submenu:0,subsect:[],successor:3,suffix:5,suggest:5,sum:5,sumcashbi:5,sumcashornul:5,summaris:3,supertyp:5,support:[3,4,5],suppos:5,surround:5,swap:4,synchronis:[3,4],syntax:[3,5],system:[2,3,5],tailor:1,take:[2,5],target:3,task:[3,4],teach:[],techniqu:5,tempt:5,ten:5,term:[3,5],terminolog:3,test:[0,2,3,4],test_tx_tim:5,testutil:5,text:0,than:[1,3,5],thei:[3,5],them:[2,4,5],themselv:3,therefor:[2,3,5],thi:[0,1,3,4,5],thing:[2,3,5],think:[0,5],third:5,those:5,though:5,thought:3,three:5,threshold:5,through:[3,5],thrown:5,thu:5,tighten:5,time:[1,3,5],timelin:5,timestamp:[3,5],todo:5,togeth:[3,5],too:5,tool:3,top:5,tostr:5,total:5,tracker:2,trade:[3,4,5],tradit:5,transact:[1,3,4,5],transactionforverif:5,transactiongroup:5,transactiongroupfortest:5,transfer:5,transit:5,treat:5,tri:5,tripl:3,tsa:3,tsp:3,ture:3,turn:5,twice:3,two:[2,3,5],txhash:3,type:[3,5],under:5,underscor:5,understand:[],unexecut:5,uniqu:3,unit:[0,2,3,4,5],unlik:5,unnecessari:5,unrecognis:5,unspent:3,unsupportedoperationexcept:5,unusu:5,unwieldi:5,updat:[0,3,5],upgrad:0,upon:[3,5],url:0,usabl:3,usag:5,user:[1,2,3,4],util:[3,5],utxo:3,val:5,valid:[3,5],valu:[3,5],vari:5,variant:5,variou:[3,4,5],vendor:2,verbos:5,veri:3,verif:[2,3],verifi:[],version:[0,2,5],virtual:3,visibl:3,wai:[3,5],wait:0,wallet:3,want:[0,5],websit:5,well:[2,3,5],were:5,what:[],when:5,where:3,wherea:5,which:[2,3,5],whilst:[3,5],who:3,whole:5,why:[3,5],wide:5,wiki:[3,5],wikipedia:5,wish:4,within:[3,4],without:[],withoutown:5,work:[0,2,3,5],world:5,worn:5,worri:3,worth:5,would:[2,5],wouldn:5,wrap:5,write:[3,5],written:[3,5],www:0,xxxx:[],yeah:[],yet:[3,5],yield:3,you:[0,2,3,5],your:[],your_usernam:0,zero:5},titles:["Getting set up","Welcome to the Playground’s documentation!","What’s included?","Overview","Roadmap","Tutorial"],titleterms:{"class":5,"function":5,api:5,asset:5,base:5,bitcoin:3,cash:[],check:5,command:5,commerci:5,comparison:3,contract:[3,5],craft:5,data:3,defin:[],document:1,ethereum:3,fungibl:5,get:0,how:5,includ:2,indic:[],intellij:0,kotlin:3,mileston:4,model:3,non:5,orient:5,overview:3,paper:5,playground:1,requir:5,roadmap:4,set:0,smart:5,start:5,state:5,subsect:[],tabl:[],test:5,tutori:5,understand:5,verifi:5,welcom:1,what:2,without:0,your:5}}) \ No newline at end of file +Search.setIndex({envversion:46,filenames:["getting-set-up","index","inthebox","overview","roadmap","tutorial"],objects:{},objnames:{},objtypes:{},terms:{"8u45":0,"boolean":5,"break":5,"byte":3,"case":[3,4,5],"catch":0,"class":[],"default":[0,5],"final":[4,5],"function":[],"import":[0,3,5],"instanceof":5,"int":5,"long":5,"new":[3,5],"null":5,"public":[2,3,5],"return":5,"short":5,"static":5,"switch":5,"throw":5,"true":5,"try":[3,5],"var":5,"void":5,abil:[3,5],about:[3,4,5],abov:5,accept:[3,5],accident:5,account:3,actor:5,actual:5,add:5,addit:5,address:[3,5],admin:4,administr:2,advanc:4,affection:5,after:[3,5],again:5,against:5,agre:[0,3],algorithm:[2,3],alic:5,alicegetsback:5,all:[0,3,5],allow:[3,5],almost:5,along:[3,5],alreadi:5,also:[0,3,5],alt:5,alter:5,although:[3,5],alwai:[3,5],amount:[2,5],ani:[3,5],annot:5,anoth:5,anyon:5,anyth:[3,5],anywher:5,api:[2,3,4],appear:[3,5],applic:3,approach:[3,5],arbitrari:[3,5],arbitrarili:3,aren:5,arg:5,argument:[3,5],around:3,arrai:3,articl:3,artifact:5,ask:5,assembl:3,assert:5,asset:3,assist:5,associ:[3,5],assum:5,atom:5,attach:[3,5],attempt:3,audit:3,authenticatedobject:5,author:3,auto:5,autom:5,automat:5,avail:5,await:5,back:5,background:3,backtick:5,bad:5,balanc:5,bankrupt:5,base:3,basic:[3,5],bear:5,becaus:5,becom:5,been:[3,5],befor:[3,5],begin:[3,5],behav:5,behaviour:2,behind:5,benefit:5,beta:0,better:[1,3,5],between:5,beyond:[3,5],bill:5,bind:3,bit:5,bitbucket:0,blah:[],blank:5,block:[3,5],bob:5,bond:5,bookkeep:3,boost:2,both:[3,5],brows:2,bug:2,build:[0,3,5],builder:5,built:5,bunch:5,bundl:3,busi:[3,5],bytecod:[3,5],c25c001e26e3:[],calcul:5,call:[3,5],can:[0,2,3,5],cannot:[3,5],canon:4,carefulli:3,cash:[],cashkt:5,caus:5,center:5,certain:3,cev:0,chain:[3,5],chang:5,check:[],choos:0,claim:[2,3,5],click:0,cmd:5,code:[0,1,2,3,4,5],codebas:5,collect:5,com:0,combin:5,come:3,command:[],commerci:[],commercial_pap:5,commercialpap:[3,5],commercialpapertest:5,common:5,commonli:5,commun:0,companion:5,compar:3,compil:5,complet:[3,5],complex:[3,5],concept:[3,5],concern:5,configur:0,conflict:3,connect:5,consid:[3,5],consist:[2,3],constant:5,construct:5,consum:3,contain:[3,5],content:[3,5],contract:[],contractst:5,contrast:3,contribut:5,control:[0,3,5],copi:5,core:5,correct:5,correctli:[3,5],correspond:5,cost:5,could:5,coupl:[],cours:5,cover:[3,5],cp_program_id:5,craft:[],creat:[3,5],creation:5,crisp:5,crop:3,currenc:[3,5],current:[2,3,5],curv:2,dai:5,data:[],databas:[1,2],date:5,datetim:3,decid:[3,5],declar:5,defin:[],definit:5,delet:5,deliveri:5,demand:3,denomin:3,depend:[0,5],deposit:3,depth:5,deriv:5,describ:[1,5],design:[1,3,5],desir:5,despit:5,destroi:[3,5],destroypaperatredempt:5,detail:[3,5],develop:3,didn:5,differ:[3,5],digit:[3,5],direct:5,directori:[0,5],dirti:5,disallow:5,disk:4,disput:5,distinguish:5,distribut:[2,3],doc:5,doe:[1,2,3,4,5],doesn:[3,5],dollar:5,domain:5,don:[0,3,5],done:3,doubl:5,doubt:3,down:5,download:0,drive:3,dsl:[4,5],due:[3,5],dummi:5,dummy_pubkey_1:5,duplic:5,durat:5,dynam:[4,5],each:[3,5],easi:5,easier:5,edit:0,editor:0,effect:5,either:5,element:3,ellipt:2,els:5,emb:5,embed:3,emit:5,empti:5,enabl:5,encount:3,end:[3,5],enforc:[3,5],engin:5,english:5,enough:[4,5],ensur:[3,5],enter:5,entir:[3,5],entiti:5,entri:3,envisag:5,equal:5,equival:5,essenti:5,etc:5,even:[3,5],everi:[3,5],everyon:[],everyth:5,evolv:[4,5],exact:5,exactli:[3,5],examin:[3,5],exampl:[4,5],excel:[],except:5,execut:[3,5],exist:[1,3,5],expect:[2,5],expectfailureoftx:5,explain:5,explicitli:[3,5],explor:[0,1,2,4,5],expos:3,express:[3,5],extend:[3,5],extens:5,extern:2,extract:[3,5],extrem:5,face:[3,5],facevalu:5,fact:5,factor:3,fail:5,failur:5,fake:5,fals:5,familiar:[3,5],far:5,favour:5,featur:5,feel:5,few:[3,5],field:5,file:5,filterisinst:5,financi:[1,3],find:3,first:[0,1,4,5],firstli:5,fit:3,fix:3,flexibl:3,follow:5,foo:[],fooutil:5,forget:5,form:5,formal:5,format:3,four:5,framework:[2,3],free:3,freeform:5,freshli:5,from:[0,3,5],front:5,full:5,fun:5,fundament:[1,5],fungibl:[],futur:[3,4,5],gain:2,gcd:3,gener:5,get:[],getclass:5,getcommand:5,getfacevalu:5,getinput:5,getissu:5,getlegalcontractrefer:5,getmaturityd:5,getoutput:5,getown:5,getprogramref:5,getsign:5,getter:5,gettim:5,getvalu:5,git:0,give:[3,4,5],given:[3,5],global:[3,4,5],goal:[1,2,3],gone:5,good:[4,5],gradl:[0,3],gradlew:0,graph:[3,4,5],green:0,group:[3,5],groupstat:5,guava:3,hack:3,had:5,hand:5,handl:[3,5],happen:5,hash:[2,3,5],hashcod:5,have:[3,4,5],haven:5,heart:5,heavili:3,held:5,hello:[],help:4,her:5,here:[3,5],higher:[0,5],highlight:5,hit:0,hold:3,holder:5,how:3,howev:5,html:[],http:[0,5],idea:[0,2,3,5],ident:[3,5],identifi:3,ietf:3,ignor:5,illegalargumentexcept:5,illegalstateexcept:5,immut:[3,5],implement:[2,3,4,5],implicitli:5,impos:5,improv:[3,4,5],includ:[],independ:5,index:[3,5],individu:5,industri:[1,3],infer:5,infix:5,inform:[3,5],inherit:5,initi:[4,5],inoutgroup:5,input:[3,5],insid:[3,5],instal:0,instanc:[3,5],instant:5,instanti:3,instead:[2,3,5],institut:[3,5],institutionrefer:5,instruct:[],integ:5,integr:2,intellij:[],intend:3,intent:5,interact:3,interest:[4,5],interfac:[1,2,4,5],intern:3,internet:3,interop:[3,5],interpret:3,intersect:5,introduct:3,invalid:5,invari:5,invok:[3,5],involv:5,ipsum:[],isaft:5,isempti:5,isn:5,issu:[3,5],issuanc:5,issuer:5,item:[0,5],iter:5,itself:[3,5],java:[3,5],javacommercialpap:5,javas:[],jdk:[0,5],jetbrain:[0,3],jira:[2,4],join:5,joint:5,junit:[3,5],just:[0,3,4,5],jvm:3,keep:[3,5],kei:[2,3,5],key_mismatch_at_issu:5,keypair:5,keyword:5,kind:[3,4,5],know:3,known:3,kotin:5,kotlin:[],kotlinlang:[],kryo:3,label:5,labori:5,languag:[3,5],later:[2,5],latest:0,latter:5,layer:4,lazili:5,lead:5,learn:[1,4],least:5,ledger:[1,3,4,5],legal:5,legalcontractrefer:5,less:5,let:[3,5],level:5,librari:[3,5],lifecycl:5,lift:4,like:[3,5],likewis:5,limit:[3,5],line:[0,5],list:5,liter:3,littl:5,load:[4,5],local:[0,3],lock:5,logic:[3,5],logo:0,look:5,loop:5,lorem:[],machin:3,made:1,mai:[3,5],main:5,maintain:3,make:5,maker:3,manag:5,mani:[2,3,5],map:5,mark:5,marker:5,market:1,match:[3,5],matur:5,maturityd:5,maximis:3,mean:3,measur:5,mechan:5,medium:[],meet:5,mega_corp:5,mega_corp_kei:5,megacorp:5,menu:0,mere:[3,5],merg:[3,5],messag:[3,5],method:5,might:5,mileston:[],mind:5,mine:3,minimum:3,minu:5,minut:3,mismatch:[],miss:5,model:[],modif:5,modifi:[0,5],modul:5,monei:5,monetari:5,more:[3,4,5],most:5,move:5,much:[3,5],multi:5,multipl:[3,5],must:[3,5],mutabl:3,name:[3,5],natur:5,necessarili:5,need:[1,3,5],net:5,network:[1,2,4],neutral:2,never:3,next:[0,4,5],nicer:[],node:3,non:3,normal:5,not_matured_at_redempt:5,note:[0,3,5],noth:[3,5],notic:5,notion:[2,3,5],notnul:5,now:[3,5],nugget:5,nullpublickei:5,number:5,obj:5,object:[3,5],obsolet:2,obvious:5,occur:5,octskyward:[],odd:5,off:5,offic:[],often:[3,5],onc:[3,5],onli:[3,5],onto:5,opaqu:3,opaquebyt:5,open:0,openjdk:0,opposit:5,option:5,oracl:0,order:[2,3,5],ordinari:[3,5],org:[0,5],orient:[],origin:5,other:[2,3,5],otherwis:5,our:[3,5],out:[0,3,4,5],outpoint:3,output:[3,5],outsid:5,outstat:5,over:5,overrid:5,overview:[],own:[3,5],owned_bi:5,owner:5,ownership:5,owningkei:5,packet:3,page:4,pai:5,pair:3,paper:[],paper_1:5,parallel:5,paramet:5,parameteris:3,part:[3,5],parti:5,particip:3,pass:[4,5],past:5,path:5,pattern:[3,5],payment:5,peer:2,pend:4,penni:5,peopl:[3,5],perform:[4,5],perhap:5,perman:[3,5],persist:2,perspect:5,piec:[3,5],place:[2,3,4,5],platform:[1,3,4,5],pleas:3,plugin:0,point:[3,5],pointer:3,poor:3,popular:3,possibl:[3,4,5],potenti:3,pound:5,power:3,practic:[3,5],pre:5,preced:5,present:[1,5],press:5,pretti:5,prevent:5,primari:3,primit:5,privaci:[4,5],privat:[3,4,5],probabl:0,problem:5,produc:5,product:[2,5],profit:5,program:[3,5],programref:5,progress:5,project:0,proof:3,propag:5,properti:5,protocol:[2,3,5],prototyp:[1,2,3,4,5],prove:[3,5],provid:[3,5],publickei:5,pull:0,pure:3,purpos:[3,5],put:5,quantiti:[3,5],quickli:5,quit:5,random:3,rapid:2,rate:4,rather:[3,5],rational:3,read:[1,2,3,5],readabl:3,real:[2,5],realiti:5,realli:5,reason:5,receiv:[3,5],recipi:5,record:5,redeem:[3,5],redempt:5,redemptiontim:5,refer:[3,5],refin:3,reflect:5,registri:3,regular:[3,5],reject:5,rel:3,relat:5,relationship:5,releas:4,relev:3,reli:3,relianc:3,remain:5,rememb:5,remov:5,replac:5,replic:3,report:[],repositori:[3,5],repres:[3,5],requir:[],requiresinglecommand:5,requirethat:5,resolut:3,rest:3,restart:0,result:[3,5],reveal:5,rfc:3,right:0,rigid:3,roadmap:[],root:5,rule:5,run:[0,3,5],safe:[3,5],sai:[3,5],same:[3,5],sandbox:[2,3,4,5],save:5,scala:[3,5],scalabl:[3,4,5],scene:5,scope:[3,5],screen:0,script:[3,5],seal:[],seamless:3,search:[0,5],second:5,secp256r1:2,section:5,secur:3,securehash:5,see:5,seen:5,select:[0,5],semi:3,send:3,sens:[],separ:5,serial:[2,5],serialis:[2,3],serializablewithkryo:5,serializeablewithkryo:5,set:[],setter:5,sever:[3,5],sha256:5,sha:3,share:[1,3,5],she:5,shortcut:2,shorthand:5,should:[0,2,3,5],show:[0,3,5],shown:5,sig:5,sign:[2,3,5],signatur:[2,3,5],signer:5,similar:[3,5],similarli:5,simpl:[4,5],simpler:3,simpli:5,simplifi:[2,3,5],simultan:5,singl:[3,5],singleornul:[],singleton:5,site:4,size:5,slight:5,slightli:5,small:[2,3,5],smart:2,smooth:5,snippet:5,softwar:2,sold:5,solv:5,some:[2,3,4,5],somed:5,someon:5,someprofit:5,someth:[4,5],sometim:[3,5],somewhat:3,somewher:5,sort:3,sound:5,space:5,specif:[3,5],specifi:[2,5],spend:[3,5],split:[3,5],src:5,stage:[4,5],stai:3,standard:[3,5],standardis:[3,5],start:[],state:[],stateless:3,statement:5,stateref:3,step:5,still:[3,5],storag:[3,4],store:5,straightforward:5,string:5,strong:3,structur:[2,3,5],studi:5,sub:4,subgroup:[3,4],submenu:0,subsect:[],successor:3,suffix:5,suggest:5,sum:5,sumcashbi:5,sumcashornul:5,summaris:3,supertyp:5,support:[3,4,5],suppos:5,surround:5,swap:4,synchronis:[3,4],syntax:[3,5],system:[2,3,5],tailor:1,take:[2,5],target:3,task:[3,4],teach:[],techniqu:5,tempt:5,ten:5,term:[3,5],terminolog:3,test:[0,2,3,4],test_tx_tim:5,testutil:5,text:0,than:[1,3,5],thei:[3,5],them:[2,4,5],themselv:3,therefor:[2,3,5],thi:[0,1,3,4,5],thing:[2,3,5],think:[0,5],third:5,those:5,though:5,thought:3,three:5,threshold:5,through:[3,5],thrown:5,thu:5,tighten:5,time:[1,3,5],timelin:5,timestamp:[3,5],todo:5,togeth:[3,5],too:5,tool:3,top:5,tostr:5,total:5,tracker:2,trade:[3,4,5],tradit:5,transact:[1,3,4,5],transactionforverif:5,transactiongroup:5,transactiongroupfortest:5,transfer:5,transit:5,treat:5,tri:5,tripl:3,tsa:3,tsp:3,ture:3,turn:5,twice:3,two:[2,3,5],txhash:3,type:[3,5],under:5,underscor:5,understand:[],unexecut:5,unfortun:5,uniqu:3,unit:[0,2,3,4,5],unlik:5,unnecessari:5,unrecognis:5,unspent:3,unsupportedoperationexcept:5,unusu:5,unwieldi:5,updat:[0,3,5],upgrad:0,upon:[3,5],url:0,usabl:3,usag:5,user:[1,2,3,4],util:[3,5],utxo:3,val:5,valid:[3,5],valu:[3,5],vari:5,variant:5,variou:[3,4,5],vendor:2,verbos:5,veri:3,verif:[2,3],verifi:[],version:[0,2,5],virtual:3,visibl:3,wai:[3,5],wait:0,wallet:3,want:[0,5],websit:5,well:[2,3,5],were:5,what:[],when:5,where:3,wherea:5,which:[2,3,5],whilst:[3,5],who:3,whole:5,why:[3,5],wide:5,wiki:[3,5],wikipedia:5,wish:4,within:[3,4],without:[],withoutown:5,won:5,work:[0,2,3,5],world:5,worn:5,worri:3,worth:5,would:[2,5],wouldn:5,wrap:5,write:[3,5],written:[3,5],www:0,xxxx:[],yeah:[],yet:[3,5],yield:3,you:[0,2,3,5],your:[],your_usernam:0,zero:5},titles:["Getting set up","Welcome to the Playground’s documentation!","What’s included?","Overview","Roadmap","Tutorial"],titleterms:{"class":5,"function":5,api:5,asset:5,base:5,bitcoin:3,cash:[],check:5,command:5,commerci:5,comparison:3,contract:[3,5],craft:5,data:3,defin:[],document:1,ethereum:3,fungibl:5,get:0,how:5,includ:2,indic:[],intellij:0,kotlin:3,mileston:4,model:3,non:5,orient:5,overview:3,paper:5,playground:1,requir:5,roadmap:4,set:0,smart:5,start:5,state:5,subsect:[],tabl:[],test:5,tutori:5,understand:5,verifi:5,welcom:1,what:2,without:0,your:5}}) \ No newline at end of file diff --git a/docs/build/html/tutorial.html b/docs/build/html/tutorial.html index 83faaff05d..a35a70777c 100644 --- a/docs/build/html/tutorial.html +++ b/docs/build/html/tutorial.html @@ -418,7 +418,8 @@ trade many different pieces of commercial paper in a single atomic step.

After extracting the command and the groups, we then iterate over each group and verify it meets the required business logic.

-
for (group in groups) {
+
val time = tx.time
+for (group in groups) {
     when (command.value) {
         is Commands.Move -> {
             val input = group.inputs.single()
@@ -431,8 +432,9 @@ logic.

is Commands.Redeem -> { val input = group.inputs.single() val received = tx.outStates.sumCashBy(input.owner) + if (time == null) throw IllegalArgumentException("Redemption transactions must be timestamped") requireThat { - "the paper must have matured" by (input.maturityDate < tx.time) + "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 group.outputs.isEmpty() "the transaction is signed by the owner of the CP" by (command.signers.contains(input.owner)) @@ -441,12 +443,13 @@ logic.

is Commands.Issue -> { val output = group.outputs.single() + if (time == null) throw IllegalArgumentException("Issuance transactions must be timestamped") requireThat { // Don't allow people to issue commercial paper under other entities identities. "the issuance is signed by the claimed issuer of the paper" by (command.signers.contains(output.issuance.institution.owningKey)) "the face value is not zero" by (output.faceValue.pennies > 0) - "the maturity date is not in the past" by (output.maturityDate > tx.time) + "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. "there is no input state" by group.inputs.isEmpty() } @@ -458,7 +461,8 @@ logic.

}
-
for (InOutGroup<State> group : groups) {
+
Instant time = tx.getTime();   // Can be null/missing.
+for (InOutGroup<State> group : groups) {
     List<State> inputs = group.getInputs();
     List<State> outputs = group.getOutputs();
 
@@ -478,9 +482,11 @@ logic.

throw new IllegalStateException("Failed requirement: the output state is the same as the input state except for owner"); } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Redeem) { Amount received = CashKt.sumCashOrNull(inputs); + if (time == null) + throw new IllegalArgumentException("Redemption transactions must be timestamped"); if (received == null) throw new IllegalStateException("Failed requirement: no cash being redeemed"); - if (input.getMaturityDate().isAfter(tx.getTime())) + if (input.getMaturityDate().isAfter(time)) throw new IllegalStateException("Failed requirement: the paper must have matured"); if (!input.getFaceValue().equals(received)) throw new IllegalStateException("Failed requirement: the received amount equals the face value"); @@ -494,6 +500,15 @@ logic.

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 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 diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst index d30268c2b8..17926030e6 100644 --- a/docs/source/tutorial.rst +++ b/docs/source/tutorial.rst @@ -320,6 +320,7 @@ logic. .. sourcecode:: kotlin + val time = tx.time for (group in groups) { when (command.value) { is Commands.Move -> { @@ -333,8 +334,9 @@ logic. is Commands.Redeem -> { val input = group.inputs.single() val received = tx.outStates.sumCashBy(input.owner) + if (time == null) throw IllegalArgumentException("Redemption transactions must be timestamped") requireThat { - "the paper must have matured" by (input.maturityDate < tx.time) + "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 group.outputs.isEmpty() "the transaction is signed by the owner of the CP" by (command.signers.contains(input.owner)) @@ -343,12 +345,13 @@ logic. is Commands.Issue -> { val output = group.outputs.single() + if (time == null) throw IllegalArgumentException("Issuance transactions must be timestamped") requireThat { // Don't allow people to issue commercial paper under other entities identities. "the issuance is signed by the claimed issuer of the paper" by (command.signers.contains(output.issuance.institution.owningKey)) "the face value is not zero" by (output.faceValue.pennies > 0) - "the maturity date is not in the past" by (output.maturityDate > tx.time) + "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. "there is no input state" by group.inputs.isEmpty() } @@ -361,6 +364,7 @@ logic. .. sourcecode:: java + Instant time = tx.getTime(); // Can be null/missing. for (InOutGroup group : groups) { List inputs = group.getInputs(); List outputs = group.getOutputs(); @@ -381,9 +385,11 @@ logic. throw new IllegalStateException("Failed requirement: the output state is the same as the input state except for owner"); } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Redeem) { Amount received = CashKt.sumCashOrNull(inputs); + if (time == null) + throw new IllegalArgumentException("Redemption transactions must be timestamped"); if (received == null) throw new IllegalStateException("Failed requirement: no cash being redeemed"); - if (input.getMaturityDate().isAfter(tx.getTime())) + if (input.getMaturityDate().isAfter(time)) throw new IllegalStateException("Failed requirement: the paper must have matured"); if (!input.getFaceValue().equals(received)) throw new IllegalStateException("Failed requirement: the received amount equals the face value"); @@ -396,6 +402,14 @@ logic. 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 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 diff --git a/src/contracts/Cash.kt b/src/contracts/Cash.kt index d5d5c4edc1..4f49334621 100644 --- a/src/contracts/Cash.kt +++ b/src/contracts/Cash.kt @@ -56,7 +56,7 @@ class Cash : Contract { // Just for grouping interface Commands : Command { - object Move : Commands + class Move() : TypeOnlyCommand(), Commands /** * Allows new cash states to be issued into existence: the nonce ("number used once") ensures the transaction @@ -210,7 +210,7 @@ class Cash : Contract { for (state in gathered) tx.addInputState(state.ref) for (state in outputs) tx.addOutputState(state) // What if we already have a move command with the right keys? Filter it out here or in platform code? - tx.addArg(WireCommand(Commands.Move, keysUsed.toList())) + tx.addArg(WireCommand(Commands.Move(), keysUsed.toList())) } } diff --git a/src/contracts/CommercialPaper.kt b/src/contracts/CommercialPaper.kt index fbc76c76b4..b542f10cec 100644 --- a/src/contracts/CommercialPaper.kt +++ b/src/contracts/CommercialPaper.kt @@ -40,11 +40,11 @@ class CommercialPaper : Contract { } interface Commands : Command { - object Move : Commands - object Redeem : Commands + class Move : TypeOnlyCommand(), Commands + class Redeem : TypeOnlyCommand(), Commands // We don't need a nonce in the issue command, because the issuance.reference field should already be unique per CP. // However, nothing in the platform enforces that uniqueness: it's up to the issuer. - object Issue : Commands + class Issue : TypeOnlyCommand(), Commands } override fun verify(tx: TransactionForVerification) { @@ -54,6 +54,7 @@ class CommercialPaper : Contract { // 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() + val time = tx.time for (group in groups) { when (command.value) { @@ -68,8 +69,9 @@ class CommercialPaper : Contract { is Commands.Redeem -> { val input = group.inputs.single() val received = tx.outStates.sumCashBy(input.owner) + if (time == null) throw IllegalArgumentException("Redemption transactions must be timestamped") requireThat { - "the paper must have matured" by (input.maturityDate < tx.time) + "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 group.outputs.isEmpty() "the transaction is signed by the owner of the CP" by (command.signers.contains(input.owner)) @@ -78,12 +80,13 @@ class CommercialPaper : Contract { is Commands.Issue -> { val output = group.outputs.single() + if (time == null) throw IllegalArgumentException("Redemption transactions must be timestamped") requireThat { // Don't allow people to issue commercial paper under other entities identities. "the issuance is signed by the claimed issuer of the paper" by (command.signers.contains(output.issuance.institution.owningKey)) "the face value is not zero" by (output.faceValue.pennies > 0) - "the maturity date is not in the past" by (output.maturityDate > tx.time) + "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. "there is no input state" by group.inputs.isEmpty() } @@ -102,7 +105,7 @@ class CommercialPaper : Contract { */ fun craftIssue(issuance: InstitutionReference, faceValue: Amount, maturityDate: Instant): PartialTransaction { val state = State(issuance, issuance.institution.owningKey, faceValue, maturityDate) - return PartialTransaction(state, WireCommand(Commands.Issue, issuance.institution.owningKey)) + return PartialTransaction(state, WireCommand(Commands.Issue(), issuance.institution.owningKey)) } /** @@ -111,7 +114,7 @@ class CommercialPaper : Contract { fun craftMove(tx: PartialTransaction, paper: StateAndRef, newOwner: PublicKey) { tx.addInputState(paper.ref) tx.addOutputState(paper.state.copy(owner = newOwner)) - tx.addArg(WireCommand(Commands.Move, paper.state.owner)) + tx.addArg(WireCommand(Commands.Move(), paper.state.owner)) } /** @@ -126,7 +129,7 @@ class CommercialPaper : Contract { // Add the cash movement using the states in our wallet. Cash().craftSpend(tx, paper.state.faceValue, paper.state.owner, wallet) tx.addInputState(paper.ref) - tx.addArg(WireCommand(CommercialPaper.Commands.Redeem, paper.state.owner)) + tx.addArg(WireCommand(CommercialPaper.Commands.Redeem(), paper.state.owner)) } } diff --git a/src/contracts/JavaCommercialPaper.java b/src/contracts/JavaCommercialPaper.java index 814c5f11a7..cb622c986d 100644 --- a/src/contracts/JavaCommercialPaper.java +++ b/src/contracts/JavaCommercialPaper.java @@ -109,6 +109,8 @@ public class JavaCommercialPaper implements Contract { // Find the command that instructs us what to do and check there's exactly one. AuthenticatedObject cmd = requireSingleCommand(tx.getCommands(), Commands.class); + Instant time = tx.getTime(); // Can be null/missing. + for (InOutGroup group : groups) { List inputs = group.getInputs(); List outputs = group.getOutputs(); @@ -129,9 +131,11 @@ public class JavaCommercialPaper implements Contract { throw new IllegalStateException("Failed requirement: the output state is the same as the input state except for owner"); } else if (cmd.getValue() instanceof JavaCommercialPaper.Commands.Redeem) { Amount received = CashKt.sumCashOrNull(inputs); + if (time == null) + throw new IllegalArgumentException("Redemption transactions must be timestamped"); if (received == null) throw new IllegalStateException("Failed requirement: no cash being redeemed"); - if (input.getMaturityDate().isAfter(tx.getTime())) + if (input.getMaturityDate().isAfter(time)) throw new IllegalStateException("Failed requirement: the paper must have matured"); if (!input.getFaceValue().equals(received)) throw new IllegalStateException("Failed requirement: the received amount equals the face value"); diff --git a/src/core/Crypto.kt b/src/core/Crypto.kt index fb000511b4..26ad4ca8b0 100644 --- a/src/core/Crypto.kt +++ b/src/core/Crypto.kt @@ -63,6 +63,8 @@ class DummyPublicKey(val s: String) : PublicKey, Comparable, Serializ override fun getEncoded() = s.toByteArray() override fun getFormat() = "ASN.1" override fun compareTo(other: PublicKey): Int = BigInteger(encoded).compareTo(BigInteger(other.encoded)) + override fun equals(other: Any?) = other is DummyPublicKey && other.s == s + override fun hashCode(): Int = s.hashCode() override fun toString() = "PUBKEY[$s]" } diff --git a/src/core/Structures.kt b/src/core/Structures.kt index c3b6c9738f..8f9cbcfd55 100644 --- a/src/core/Structures.kt +++ b/src/core/Structures.kt @@ -49,6 +49,12 @@ data class InstitutionReference(val institution: Institution, val reference: Opa /** Marker interface for classes that represent commands */ interface Command : SerializeableWithKryo +/** Commands that inherit from this are intended to have no data items: it's only their presence that matters. */ +abstract class TypeOnlyCommand : Command { + override fun equals(other: Any?) = other?.javaClass == javaClass + override fun hashCode() = javaClass.name.hashCode() +} + /** Wraps an object that was signed by a public key, which may be a well known/recognised institutional key. */ data class AuthenticatedObject( val signers: List, diff --git a/src/core/Transactions.kt b/src/core/Transactions.kt index 435efae491..1c07c6ff58 100644 --- a/src/core/Transactions.kt +++ b/src/core/Transactions.kt @@ -51,7 +51,7 @@ data class WireTransaction(val inputStates: List, val commands: List) : SerializeableWithKryo { fun serializeForSignature(): ByteArray = serialize() - fun toLedgerTransaction(timestamp: Instant, institutionKeyMap: Map, originalHash: SecureHash): LedgerTransaction { + fun toLedgerTransaction(timestamp: Instant?, institutionKeyMap: Map, originalHash: SecureHash): LedgerTransaction { val authenticatedArgs = commands.map { val institutions = it.pubkeys.mapNotNull { pk -> institutionKeyMap[pk] } AuthenticatedObject(it.pubkeys, institutions, it.command) @@ -133,6 +133,7 @@ class PartialTransaction(private val inputStates: MutableList */ interface TimestamperService { fun timestamp(hash: SecureHash): ByteArray + fun verifyTimestamp(hash: SecureHash, signedTimestamp: ByteArray): Instant } data class SignedWireTransaction(val txBits: ByteArray, val sigs: List) : SerializeableWithKryo { @@ -170,10 +171,14 @@ data class SignedWireTransaction(val txBits: ByteArray, val sigs: List): LedgerTransaction { + val stx: SignedWireTransaction = signedWireTX.deserialize() + val wtx: WireTransaction = stx.verify() + val instant: Instant? = if (timestamp.size != 0) timestamper.verifyTimestamp(signedWireTX.sha256(), timestamp) else null + return wtx.toLedgerTransaction(instant, institutionKeyMap, transactionID) + } } /** @@ -202,8 +214,8 @@ data class LedgerTransaction( val outStates: List, /** Arbitrary data passed to the program of each input state. */ val commands: List>, - /** The moment the transaction was timestamped for */ - val time: Instant, + /** The moment the transaction was timestamped for, if a timestamp was present. */ + val time: Instant?, /** The hash of the original serialised TimestampedWireTransaction or SignedTransaction */ val hash: SecureHash // TODO: nLockTime equivalent? @@ -223,7 +235,7 @@ data class LedgerTransaction( data class TransactionForVerification(val inStates: List, val outStates: List, val commands: List>, - val time: Instant, + val time: Instant?, val origHash: SecureHash) { override fun hashCode() = origHash.hashCode() override fun equals(other: Any?) = other is TransactionForVerification && other.origHash == origHash diff --git a/src/core/Utils.kt b/src/core/Utils.kt index 109570382d..faca5cba59 100644 --- a/src/core/Utils.kt +++ b/src/core/Utils.kt @@ -26,4 +26,4 @@ open class OpaqueBytes(val bits: ByteArray) : SerializeableWithKryo { val Int.days: Duration get() = Duration.ofDays(this.toLong()) val Int.hours: Duration get() = Duration.ofHours(this.toLong()) val Int.minutes: Duration get() = Duration.ofMinutes(this.toLong()) -val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong()) \ No newline at end of file +val Int.seconds: Duration get() = Duration.ofSeconds(this.toLong()) diff --git a/src/core/serialization/Kryo.kt b/src/core/serialization/Kryo.kt index 04d184d38c..b16a5b9817 100644 --- a/src/core/serialization/Kryo.kt +++ b/src/core/serialization/Kryo.kt @@ -12,6 +12,7 @@ import core.* import java.io.ByteArrayOutputStream import java.lang.reflect.InvocationTargetException import java.security.KeyPairGenerator +import java.security.PublicKey import java.time.Instant import java.util.* import kotlin.reflect.KClass @@ -209,6 +210,7 @@ fun createKryo(): Kryo { register(Currency::class.java, JavaSerializer()) // Only serialises the currency code as a string. register(UNUSED_EC_KEYPAIR.private.javaClass, JavaSerializer()) register(UNUSED_EC_KEYPAIR.public.javaClass, JavaSerializer()) + register(PublicKey::class.java, JavaSerializer()) // Now register platform types. registerDataClass() @@ -220,16 +222,36 @@ fun createKryo(): Kryo { registerDataClass() registerDataClass() registerDataClass() + registerDataClass() + + // Can't use data classes for this in Kotlin 1.0 due to lack of support for inheritance: must write a manual + // serialiser instead :( + register(DigitalSignature.WithKey::class.java, object : Serializer(false, true) { + override fun write(kryo: Kryo, output: Output, sig: DigitalSignature.WithKey) { + output.writeVarInt(sig.bits.size, true) + output.write(sig.bits) + output.writeInt(sig.covering, true) + kryo.writeObject(output, sig.by) + } + + override fun read(kryo: Kryo, input: Input, type: Class): DigitalSignature.WithKey { + val sigLen = input.readVarInt(true) + val sigBits = input.readBytes(sigLen) + val covering = input.readInt(true) + val pubkey = kryo.readObject(input, PublicKey::class.java) + return DigitalSignature.WithKey(pubkey, sigBits, covering) + } + }) // TODO: This is obviously a short term hack: there needs to be a way to bundle up and register contracts. registerDataClass() - register(Cash.Commands.Move.javaClass) + register(Cash.Commands.Move::class.java) registerDataClass() registerDataClass() registerDataClass() - register(CommercialPaper.Commands.Move.javaClass) - register(CommercialPaper.Commands.Redeem.javaClass) - register(CommercialPaper.Commands.Issue.javaClass) + register(CommercialPaper.Commands.Move::class.java) + register(CommercialPaper.Commands.Redeem::class.java) + register(CommercialPaper.Commands.Issue::class.java) // And for unit testing ... registerDataClass() diff --git a/tests/contracts/CashTests.kt b/tests/contracts/CashTests.kt index e5130ea3fa..50f188e011 100644 --- a/tests/contracts/CashTests.kt +++ b/tests/contracts/CashTests.kt @@ -38,19 +38,19 @@ class CashTests { } tweak { output { outState } - arg(DUMMY_PUBKEY_2) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_2) { Cash.Commands.Move() } this `fails requirement` "the owning keys are the same as the signing keys" } tweak { output { outState } output { outState.editInstitution(MINI_CORP) } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this `fails requirement` "at least one cash input" } // Simple reallocation works. tweak { output { outState } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this.accepts() } } @@ -62,7 +62,7 @@ class CashTests { transaction { input { DummyContract.State() } output { outState } - arg { Cash.Commands.Move } + arg { Cash.Commands.Move() } this `fails requirement` "there is at least one cash input" } @@ -105,7 +105,7 @@ class CashTests { fun testMergeSplit() { // Splitting value works. transaction { - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } tweak { input { inState } for (i in 1..4) output { inState.copy(amount = inState.amount / 4) } @@ -176,7 +176,7 @@ class CashTests { input { inState } input { inState.editInstitution(MINI_CORP) } output { outState } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this `fails requirement` "at issuer MiniCorp the amounts balance" } // Can't combine two different deposits at the same issuer. @@ -197,7 +197,7 @@ class CashTests { tweak { arg(MEGA_CORP_PUBKEY) { Cash.Commands.Exit(100.DOLLARS) } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this `fails requirement` "the amounts balance" } @@ -206,7 +206,7 @@ class CashTests { this `fails requirement` "required contracts.Cash.Commands.Move command" tweak { - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this.accepts() } } @@ -219,7 +219,7 @@ class CashTests { output { inState.copy(amount = inState.amount - 200.DOLLARS).editInstitution(MINI_CORP) } output { inState.copy(amount = inState.amount - 200.DOLLARS) } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this `fails requirement` "at issuer MegaCorp the amounts balance" @@ -253,7 +253,7 @@ class CashTests { // This works. output { inState.copy(owner = DUMMY_PUBKEY_2) } output { inState.copy(owner = DUMMY_PUBKEY_2).editInstitution(MINI_CORP) } - arg(DUMMY_PUBKEY_1) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1) { Cash.Commands.Move() } this.accepts() } @@ -272,7 +272,7 @@ class CashTests { input { pounds } output { inState `owned by` DUMMY_PUBKEY_2 } output { pounds `owned by` DUMMY_PUBKEY_1 } - arg(DUMMY_PUBKEY_1, DUMMY_PUBKEY_2) { Cash.Commands.Move } + arg(DUMMY_PUBKEY_1, DUMMY_PUBKEY_2) { Cash.Commands.Move() } this.accepts() } diff --git a/tests/contracts/CommercialPaperTests.kt b/tests/contracts/CommercialPaperTests.kt index 7cdd68f4ef..f69daa1ca7 100644 --- a/tests/contracts/CommercialPaperTests.kt +++ b/tests/contracts/CommercialPaperTests.kt @@ -30,7 +30,7 @@ class CommercialPaperTests { transactionGroup { transaction { output { PAPER_1 } - arg(DUMMY_PUBKEY_1) { CommercialPaper.Commands.Issue } + arg(DUMMY_PUBKEY_1) { CommercialPaper.Commands.Issue() } } expectFailureOfTx(1, "signed by the claimed issuer") @@ -42,7 +42,7 @@ class CommercialPaperTests { transactionGroup { transaction { output { PAPER_1.copy(faceValue = 0.DOLLARS) } - arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue } + arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue() } } expectFailureOfTx(1, "face value is not zero") @@ -54,7 +54,7 @@ class CommercialPaperTests { transactionGroup { transaction { output { PAPER_1.copy(maturityDate = TEST_TX_TIME - 10.days) } - arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue } + arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue() } } expectFailureOfTx(1, "maturity date is not in the past") @@ -70,7 +70,7 @@ class CommercialPaperTests { transaction { input("paper") output { PAPER_1 } - arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue } + arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue() } } expectFailureOfTx(1, "there is no input state") @@ -101,7 +101,7 @@ class CommercialPaperTests { // Some CP is issued onto the ledger by MegaCorp. transaction { output("paper") { PAPER_1 } - arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue } + arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Issue() } } // The CP is sold to alice for her $900, $100 less than the face value. At 10% interest after only 7 days, @@ -111,8 +111,8 @@ class CommercialPaperTests { input("alice's $900") output { 900.DOLLARS.CASH `owned by` MEGA_CORP_PUBKEY } output("alice's paper") { "paper".output `owned by` ALICE } - arg(ALICE) { Cash.Commands.Move } - arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Move } + arg(ALICE) { Cash.Commands.Move() } + arg(MEGA_CORP_PUBKEY) { CommercialPaper.Commands.Move() } } // Time passes, and Alice redeem's her CP for $1000, netting a $100 profit. MegaCorp has received $1200 @@ -126,8 +126,8 @@ class CommercialPaperTests { if (!destroyPaperAtRedemption) output { "paper".output } - arg(MEGA_CORP_PUBKEY) { Cash.Commands.Move } - arg(ALICE) { CommercialPaper.Commands.Redeem } + arg(MEGA_CORP_PUBKEY) { Cash.Commands.Move() } + arg(ALICE) { CommercialPaper.Commands.Redeem() } } } } diff --git a/tests/core/TransactionGroupTests.kt b/tests/core/TransactionGroupTests.kt index dc5a566643..cc8ff26a61 100644 --- a/tests/core/TransactionGroupTests.kt +++ b/tests/core/TransactionGroupTests.kt @@ -20,12 +20,12 @@ class TransactionGroupTests { transaction { input("£1000") output("alice's £1000") { A_THOUSAND_POUNDS `owned by` ALICE } - arg(MINI_CORP_PUBKEY) { Cash.Commands.Move } + arg(MINI_CORP_PUBKEY) { Cash.Commands.Move() } } transaction { input("alice's £1000") - arg(ALICE) { Cash.Commands.Move } + arg(ALICE) { Cash.Commands.Move() } arg(MINI_CORP_PUBKEY) { Cash.Commands.Exit(1000.POUNDS) } } @@ -46,7 +46,7 @@ class TransactionGroupTests { val HALF = A_THOUSAND_POUNDS.copy(amount = 500.POUNDS) `owned by` BOB output { HALF } output { HALF } - arg(MINI_CORP_PUBKEY) { Cash.Commands.Move } + arg(MINI_CORP_PUBKEY) { Cash.Commands.Move() } } verify() @@ -57,7 +57,7 @@ class TransactionGroupTests { val HALF = A_THOUSAND_POUNDS.copy(amount = 500.POUNDS) `owned by` ALICE output { HALF } output { HALF } - arg(MINI_CORP_PUBKEY) { Cash.Commands.Move } + arg(MINI_CORP_PUBKEY) { Cash.Commands.Move() } } assertNotEquals(conflict1, conflict2) @@ -89,7 +89,7 @@ class TransactionGroupTests { // points nowhere. val ref = ContractStateRef(SecureHash.randomSHA256(), 0) tg.txns.add(LedgerTransaction( - listOf(ref), listOf(A_THOUSAND_POUNDS), listOf(AuthenticatedObject(listOf(BOB), emptyList(), Cash.Commands.Move)), TEST_TX_TIME, SecureHash.randomSHA256()) + listOf(ref), listOf(A_THOUSAND_POUNDS), listOf(AuthenticatedObject(listOf(BOB), emptyList(), Cash.Commands.Move())), TEST_TX_TIME, SecureHash.randomSHA256()) ) val e = assertFailsWith(TransactionResolutionException::class) { @@ -110,7 +110,7 @@ class TransactionGroupTests { input("£1000") input("£1000") output { A_THOUSAND_POUNDS.copy(amount = A_THOUSAND_POUNDS.amount * 2) } - arg(MINI_CORP_PUBKEY) { Cash.Commands.Move } + arg(MINI_CORP_PUBKEY) { Cash.Commands.Move() } } assertFailsWith(TransactionConflictException::class) { diff --git a/tests/core/serialization/TransactionSerializationTests.kt b/tests/core/serialization/TransactionSerializationTests.kt index 1b592fb5f7..fedd90a982 100644 --- a/tests/core/serialization/TransactionSerializationTests.kt +++ b/tests/core/serialization/TransactionSerializationTests.kt @@ -2,13 +2,13 @@ package core.serialization import contracts.Cash import core.* -import core.testutils.DUMMY_PUBKEY_1 -import core.testutils.MINI_CORP -import core.testutils.TestUtils +import core.testutils.* import org.junit.Before import org.junit.Test import java.security.SignatureException +import kotlin.test.assertEquals import kotlin.test.assertFailsWith +import kotlin.test.assertNull class TransactionSerializationTests { // Simple TX that takes 1000 pounds from me and sends 600 to someone else (with 400 change). @@ -23,7 +23,7 @@ class TransactionSerializationTests { @Before fun setup() { tx = PartialTransaction( - fakeStateRef, outputState, changeState, WireCommand(Cash.Commands.Move, arrayListOf(TestUtils.keypair.public)) + fakeStateRef, outputState, changeState, WireCommand(Cash.Commands.Move(), arrayListOf(TestUtils.keypair.public)) ) } @@ -69,10 +69,27 @@ class TransactionSerializationTests { // If the signature was replaced in transit, we don't like it. assertFailsWith(SignatureException::class) { val tx2 = PartialTransaction(fakeStateRef, outputState, changeState, - WireCommand(Cash.Commands.Move, arrayListOf(TestUtils.keypair2.public))) + WireCommand(Cash.Commands.Move(), arrayListOf(TestUtils.keypair2.public))) tx2.signWith(TestUtils.keypair2) signedTX.copy(sigs = tx2.toSignedTransaction().sigs).verify() } } + + @Test + fun timestamp() { + tx.signWith(TestUtils.keypair) + val ttx = tx.toSignedTransaction().toTimestampedTransactionWithoutTime() + val ltx = ttx.verifyToLedgerTransaction(DUMMY_TIMESTAMPER, TEST_KEYS_TO_CORP_MAP) + assertEquals(tx.commands().map { it.command }, ltx.commands.map { it.value }) + assertEquals(tx.inputStates(), ltx.inStateRefs) + assertEquals(tx.outputStates(), ltx.outStates) + assertNull(ltx.time) + + val ltx2: LedgerTransaction = tx. + toSignedTransaction(). + toTimestampedTransaction(DUMMY_TIMESTAMPER). + verifyToLedgerTransaction(DUMMY_TIMESTAMPER, TEST_KEYS_TO_CORP_MAP) + assertEquals(TEST_TX_TIME, ltx2.time) + } } \ No newline at end of file diff --git a/tests/core/testutils/TestUtils.kt b/tests/core/testutils/TestUtils.kt index faed264157..72a91001ff 100644 --- a/tests/core/testutils/TestUtils.kt +++ b/tests/core/testutils/TestUtils.kt @@ -2,8 +2,13 @@ package core.testutils +import com.google.common.io.BaseEncoding import contracts.* import core.* +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.DataInputStream +import java.io.DataOutputStream import java.security.KeyPairGenerator import java.security.PublicKey import java.time.Instant @@ -47,6 +52,33 @@ val TEST_PROGRAM_MAP: Map = mapOf( DUMMY_PROGRAM_ID to DummyContract ) +/** + * A test/mock timestamping service that doesn't use any signatures or security. It always timestamps with + * [TEST_TX_TIME], an arbitrary point on the timeline. + */ +class DummyTimestamper(private val time: Instant = TEST_TX_TIME) : TimestamperService { + override fun timestamp(hash: SecureHash): ByteArray { + val bos = ByteArrayOutputStream() + DataOutputStream(bos).use { + it.writeLong(time.toEpochMilli()) + it.write(hash.bits) + } + return bos.toByteArray() + } + + override fun verifyTimestamp(hash: SecureHash, signedTimestamp: ByteArray): Instant { + val dis = DataInputStream(ByteArrayInputStream(signedTimestamp)) + val epochMillis = dis.readLong() + val serHash = ByteArray(32) + dis.readFully(serHash) + if (!Arrays.equals(serHash, hash.bits)) + throw IllegalStateException("Hash mismatch: ${BaseEncoding.base16().encode(serHash)} vs ${BaseEncoding.base16().encode(hash.bits)}") + return Instant.ofEpochMilli(epochMillis) + } +} + +val DUMMY_TIMESTAMPER = DummyTimestamper() + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Defines a simple DSL for building pseudo-transactions (not the same as the wire protocol) for testing purposes.