[Impressum] [E-Mail]

package generated.javacard.copycardMoneySecure.copycard;

import javacard.framework.*;

/**
 * Generated Smartcard for copycardMoneySecure model
 */
public class Copycard extends SimpleComm {

	public short balance;
	public Secret passphrase;
	public Nonce challenge;
	public byte state;

	/**
	 * Constructor
	 */
	public Copycard() {
		balance = 0;
		passphrase = new Secret();
		challenge = new Nonce();
		state = State.APPLET_UNINITIALIZED;
	}

	public void appletInitialization(byte[] buf, short offset) {
		if (state != State.APPLET_UNINITIALIZED)
			stop();
		Coding.getInstance().decodeCopycard(buf, offset, this);
	}

	/**
	 * process-method, is called from SimpleCommCopycard when a message arrives
	 * 
	 * @param inmsg message to process
	 */
	public void process(Message inmsg) {
		if (state == State.APPLET_UNINITIALIZED)
			stop();
		switch (inmsg.getCode()) {
			case Code.REQUESTBALANCE :
				processRequestBalance((RequestBalance) inmsg);
				break;
			case Code.PAY :
				processPay((Pay) inmsg);
				break;
			case Code.AUTHENTICATE :
				processAuthenticate((Authenticate) inmsg);
				break;
			case Code.LOAD :
				processLoad((Load) inmsg);
				break;
			//Unknown Message
			default :
				stop();
		}
	}

	/**
	 * This method is called, when a -message arrives.
	 * Parameters are a result of the activity diagrams
	 */
	public void processRequestBalance(RequestBalance inmsg) {
		state = State.IDLE;
		sendMsg(Store.newResRequestBalance(balance));
	}

	/**
	 * This method is called, when a -message arrives.
	 * Parameters are a result of the activity diagrams
	 */
	public void processPay(Pay inmsg) {
		short value = inmsg.amount;
		Nonce termchallenge = inmsg.terminalchallenge;
		if (((value <= 0) || (Math.minus(balance, value) < 0))) {
			stop();
		} else {
			balance = Math.minus(balance, value);
			AuthData tmp = Store.newAuthData(Constants.PAY, passphrase,
					termchallenge, value);
			HashedData authhashed = HashedData.hash(tmp);
			sendMsg(Store.newResPay(authhashed));
		}
	}

	/**
	 * This method is called, when a -message arrives.
	 * Parameters are a result of the activity diagrams
	 */
	public void processAuthenticate(Authenticate inmsg) {
		challenge.copy(Nonce.generateNonce());
		state = State.EXPLOAD;
		sendMsg(Store.newResAuthenticate(challenge));
	}

	/**
	 * This method is called, when a -message arrives.
	 * Parameters are a result of the activity diagrams
	 */
	public void processLoad(Load inmsg) {
		short value = inmsg.amount;
		HashedData hashedauth = inmsg.authterminal;
		if (state == State.EXPLOAD) {
			state = State.IDLE;
			if (hashedauth.equals(HashedData.hash(Store.newAuthData(
					Constants.LOAD, passphrase, challenge, value)))) {
				if (!(((value <= 0) || (Math.plus(value, balance) > 20000)))) {
					balance = Math.plus(balance, value);
				} else {
					stop();
				}
			} else {
				stop();
			}
		} else {
			stop();
		}
	}

}