Advanced Programming Giuseppe Attardi Università di Pisa

Slides:



Advertisements
Similar presentations
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Review Interface, Casting, Generics, Iterator.
Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Iteration and Loop Statements Horstmann Chapter 7 Loop statements control repeated execution of a block of statements Each time the statements in the block.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Recitation 1 CS0445 Data Structures Mehmud Abliz.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
IMPLEMENTATION OF CLASS EXTENT by Paweł Świetlicki.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Exercise 1 Review OOP tirgul No Outline Polymorphism Exceptions A design example Summary.
Lecture 4b Repeating With Loops
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter No. : 1 Introduction to Java.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Chapter 5: Control Structures II
University of Central Florida COP 3330 Object Oriented Programming
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Selected Topics From Chapter 6 Iteration
Continuing Chapter 11 Inheritance and Polymorphism
CS Week 14 Jim Williams, PhD.
Functional Programming with Java
Week 6 Discussion Word Cloud.
Let’s build a Blockchain!
Exceptions & exception handling
Exceptions & exception handling
null, true, and false are also reserved.
Chapter 1: Computer Systems
Fundamental Error Handling
The Basics of Recursion
Generic Classes and Methods
Arrays and Array Lists CS 21a.
Lecture Notes – Week 2 Lecture-2
Week 4 Lecture-2 Chapter 6 (Methods).
6.001 SICP Interpretation Parts of an interpreter
Building Java Programs
Web Design & Development Lecture 6
Review for Midterm 3.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Advanced Programming Giuseppe Attardi Università di Pisa Solution MidTerm 2017 Advanced Programming Giuseppe Attardi Università di Pisa

General Remarks Follow good programming guidelines eg: https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/styleguide.md In particular: NEVER, EVER, EVER USE global variables: they hinder parallelism Use exceptions sparingly (and handle them) Use strings sparingly (StringBuffer)

Use Object Oriented Programming USE Polymorphism, USE Polymorphism makes your code more modular, more readable, more extensible Avoid using Reflection (instanceof) Avoid static methods, aka functions, in OOP Avoid functions for similar tasks: use polymorphic method in each of the classes where the operation is needed

Bad Example class Utils { static String bytesToString(); static String inputstoString(); static String outputsToString(); … } Alternative: Use method serialize() in each class

Exercise 1

Hash class Hash { private static final MessageDigest md = MessageDigest.getInstance(“SHA-256”); public byte[] code; public Hash(byte[] bytes) { code = md.digest(bytes); } boolean isValid() { return code[0] == 0 && … code[2] == 0; } boolean equals(Hash other) { return Arrays.equals(code, other.code);

Input class Input extends Pair<Hash, Integer> { // Hash for transaction, Integer for index in outputs public Input(Transaction t, int idx) { super(new Hash(t.serialize()), idx); } public byte[] serialize() { byte[] hash = getKey().code; byte bb = ByteBuffer.allocate(hash.length + 4); bb.put(hash).putInt(getValue()); return bb.array(); class Output extends Pair<Integer, PublicKey> { public Output(int v, PublicKey key) { … } public byte[] serialize() { … }

Transaction class Transaction implements Serializable { private List<Input> inputs; private List<Output> outputs; private byte[] signature; public Transaction() { inputs = new ArrayList<>(); outputs = new ArrayList<>(); } public add(Input i) { inputs.add(i); public add(Output o) { outputs.add(o);

Transaction public void sign(PrivateKey key) { Signature s = new Signature(”SHA256withRSA”); s.init(key); for (Input i : inputs) s.update(i.serialize()); for (Output o : outputs) s.update(o.serialize()); signature = s.sign(); } public byte[] serialize() { byte bs = ByteArrayOutputStream(); bs.write(i.serialize()); bs.write(o.serialize()); bs.write(signature); return bs.toByteArray();

Block class Block implements Serializable { private int seq; private int nonce = -1; private Hash previous; private Transaction t; public Block(int seq, Hash previous, Transaction t) { … } public hash() { return new Hash(serialize()); } public int mine() { Hash hash; do { nonce++; hash = this.hash(); } while (!hash.isValid()) return nonce;

Block public byte[] serialize() { byte bs = ByteArrayOutputStream(); bs.write(ByteBuffer.allocate(4).putInt(seq).array()); bs.write(ByteBuffer.allocate(4).putInt(nonce).array()); bs.write(previous.hash()); bs.write(t.serialize()); return bs.toByteArray(); }

Exercise 2

BlockChain class BlockChain { private List<Block> chain = new LinkedList<>();

boolean isValidBlockChain() { Map<Hash, BitSet> spentOutputs = new HashMap<>(); Hash current = null; // current block in chain for (Block next : chain) { // next block in chain Transaction tx = next.transaction; if (current == null) { spentOutputs.put(new Hash(tx.serialize()), new BitSet(tx.getOutputs().size())); current = next; continue; } Hash previous = current.previous(); Hash hash = next.hash(); if (!hash.isValid() || !hash.equals(previous)) // current block must refer to next one return false; for (Input input : tx.getInputs()) { if (spentOutputs.computeIfPresent(input.getKey(), // update spentOutputs (k, v) -> { if (v.get(input.getValue())) // already spent output at index input.getValue() return null; v.set(input.getValue()); // update return v; // put back into Map }) == null) return false; spentOutputs.put(new Hash(tx.serialize()), new BitSet(tx.getOutputs().size())); } return true;

public int getBalance(PublicKey user) { Map<Hash, BitSet> spentOutputs = new HashMap<>(); Iterator <Block> it = chain.descendingIterator(); // from last to first   while (it.hasNext()) { Block b = it.next(); Transaction tx = b.transaction(); Hash hash =  new Hash(tx); List<Output> outputs = tx.getOutputs();   for (int i = 0; i < outputs.size(); i++) { Output o = outputs.get(i);   if (user.equals(o.getValue()) && (spentOutputs.get(hash) == null || !spentOutputs.get(hash).get(i))) balance += o.getKey(); } // now add the outputs to the map spentOutputs for (Input in : tx.getInputs()) spentOutputs.computeIfAbsent(in.getKey(), v -> new BitSet()).set(in.getValue()));   return balance;

Exercise 3

 public static void main(String args[]) { String input; String[] tokens; Scanner reader =  new Scanner(System.in); init();   do {   do { System.out.print("> "); input = reader.nextLine().trim(); } while (input.equals("")); tokens = input.split("\\s+");   switch (tokens[0]) {   case "status": printBlockChain();   break;   case "check":   if (chain.isValidBlockChain()) System.out.println("The block chain is valid!");   else System.out.println("The block chain is not valid.");

Exercise 4

A closure is a functional object that consists of a function and the lexical environment at the time of its creation. The environment contains the bindings for the non local variables visible in the scope of the function. In C#, a delegate type is a type that represents functions with a given signature. A delegate instance is created on an object and a method on that object compatible with its signature. A delegate instance can be used as a function by invoking it with arguments, and this corresponds to invoking the delegate method on the delegate target with the given arguments.